Skip to content

Instantly share code, notes, and snippets.

@agonbina
Last active August 29, 2015 14:16
Show Gist options
  • Save agonbina/fb35a3bf49b17046dc44 to your computer and use it in GitHub Desktop.
Save agonbina/fb35a3bf49b17046dc44 to your computer and use it in GitHub Desktop.
requirebin sketch
var Map = require('indexed-map')
var Store = require('datastore')
var rooms = Map()
var keys = Map()
var equipment = Map()
var equipmentSpecs = Map()
rooms.insert('keys', keys)
rooms.insert('equipment', equipment)
equipment.insert('specs', equipmentSpecs)
function Resource(map) {
var resources = {},
self = this
map = map || Map()
map.each(function(key) {
resources[key] = function() {
console.log('Retrieving: ', key)
console.log('For ID: ', self._id)
}
})
this._map = map
this._resources = resources
}
Resource.prototype.id = function(id) {
this._id = id
return this._resources
}
var Rooms = new Resource(rooms)
console.log(Rooms.id(5).equipment())
console.log(Rooms.id(2).keys())
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(){"use strict";function IndexedMap(){if(!(this instanceof IndexedMap)){return new IndexedMap}this._map={};this._list=[]}IndexedMap.prototype={get length(){return this._list.length},get keys(){return this._list},has:function(key){return this._map.hasOwnProperty(key)},sort:function(callback){if(typeof callback==="function"){var self=this;this._list.sort(function(a,b){return callback.call(self,self._map[a],self._map[b])})}else{this._list.sort()}return this},find:function(callback,startIndex){if(typeof callback==="function"){var i=typeof startIndex==="number"&&startIndex>0?startIndex:0;for(;i<this._list.length;++i){if(callback.call(this,this._list[i],this._map[this._list[i]])===true){return this._map[this._list[i]]}}}return null},each:function(callback,startIndex){if(typeof callback!=="function"){return null}var i=typeof startIndex==="number"&&startIndex>0?startIndex:0;for(;i<this._list.length;++i){if(callback.call(this,this._list[i],this._map[this._list[i]])===false){return this}}return this},getFirst:function(){if(this._list.length){return this._map[this._list[0]]}else{return null}},getLast:function(){if(this._list.length){return this._map[this._list[this._list.length-1]]}else{return null}},getNextOf:function(key){var nextKey=this.nextKeyOf(key);if(nextKey){return this._map[nextKey]}else{return null}},getPrevOf:function(key){var prevKey=this.prevKeyOf(key);if(prevKey){return this._map[prevKey]}else{return null}},nextKeyOf:function(key){if(this.has(key)){return this._list[this._list.indexOf(key)+1]}else{return null}},prevKeyOf:function(key){if(this.has(key)){return this._list[this._list.indexOf(key)-1]}else{return null}},get:function(key){if(this.has(key)){return this._map[key]}else{return null}},getAt:function(index){return this.get(this._list[index])},set:function(key,value){if(this.has(key)){var oldValue=this._map[key];this._map[key]=value;return oldValue}else{return null}},setAt:function(index,value){return this.set(this._list[index],value)},insert:function(key,value,targetKey){return this.insertAt(key,value,this._list.indexOf(targetKey))},insertAt:function(key,value,targetIndex){if(!key||this.has(key)){return null}this._map[key]=value;if(typeof targetIndex!=="number"||targetIndex<0||targetIndex>=this._list.length){this._list.push(key);return this._map[key]}else{this._list.splice(targetIndex,0,key);return this._map[key]}},move:function(key,targetKey){if(!this.has(key)){return null}var index=this._list.indexOf(key);this._list.splice(index,1);var targetIndex=this._list.indexOf(targetKey);this._list.splice(targetIndex,0,key);return this._map[key]},moveAt:function(index,targetIndex){this.move(this._list[index],this._list[targetIndex])},remove:function(key){if(!this.has(key)){return null}var oldValue=this._map[key];delete this._map[key];var index=this._list.indexOf(key);this._list.splice(index,1);return oldValue},removeAt:function(index){return this.remove(this._list[index])}};if(typeof define==="function"&&define.amd){define("indexed-map",IndexedMap)}else if(typeof module==="object"&&typeof define!=="function"){exports=module.exports=IndexedMap}else if(window){window.IndexedMap=IndexedMap}})()},{}],2:[function(require,module,exports){module.exports={name:"indexed-map",version:"1.0.0",description:"An enhanced map that supports easy insertion or deletion at specific position. Give access to entries by index or key. Can be used instead of a linked list.",keywords:["linked","list","map","array","collection","doubly-linked","linkedlist","linkedmap","sorted","ordered","indexed","vector"],author:{name:"Tobias Lindig",email:"[email protected]"},repository:{type:"git",url:"https://github.com/tlindig/indexed-map.git"},bugs:{url:"https://github.com/tlindig/indexed-map/issues"},licenses:[{type:"MIT",url:"https://github.com/tlindig/indexed-map/blob/master/LICENSE-MIT"}],main:"index",engines:{node:">=0.6.x"},scripts:{},devDependencies:{mocha:"1.x",chai:"1.x"},readme:"# IndexedMap [![Build Status](https://travis-ci.org/tlindig/indexed-map.png?branch=master)](https://travis-ci.org/tlindig/indexed-map)\n\nAn enhanced map that supports easy insertion or deletion at specific position. Give access to entries by index or key. Can be used instead of a linked list.\n\n```\nStability: 4 - API Frozen\n```\n( see [Stability Index](http://nodejs.org/api/documentation.html#documentation_stability_index) ) \n\n## Install\n\nas node module with npm:\n```bash\nnpm install indexed-map --production\n```\n\n## Usage\n\nCan be used as node module 'indexed-map', as AMD module 'indexed-map' or as global class at `window.IndexedMap`.\n\n```js\nvar IndexedMap = require('indexed-map');\nvar myMap = IndexedMap();\n// add an entry at the end\nmyMap.insert('myKey', { myProperty:'My Value' });\n```\n\nKeys have to be of type 'string' and unique in map.\nValues can by any type, there is no restrictions.\n\nSome methods supported in two versions, one with key as reference and the\nother works with index as reference (has suffix 'At').\n\n### Constructor\n\n* `var myMap = IndexedMap();`\n* `var myMap = new IndexedMap();`\n\nKeyword `new` is optional, it will be called by IndexedMap itself, if necessary.\n\n### properties\n\n* `length` {number} the count of entries\n\n* `keys` {Array} keys in the current order\n\n It is the real keys array of the indexedMap, not a clone. So do not\n add, change or remove elements. That would result in an inconsistent state of indexedMap itself.\n\n The advantage of not cloning the key map is, that you can easily manipulate the order of keys, if you like.\n So you could use the reverse or sort method of Array.\n\n### has, get, insert, set, move, remove\n\n* `has( key:string ):boolean`\n\n checks, if given key is in map.\n\n *return* {boolean} true, if it could found otherwise false\n\n* `get( key:string ) : value|null`\n* `getAt( index:number ) : value|null`\n \n *return* Value for given key/index or null, if key was not found.\n\n* `getFirst():value|null`\n* `getLast():value|null`\n\n *return* Value of first/last entry or null, if map is empty.\n\n* `insert( key:string, value:any ):value|null`\n* `insertAt( index:number, value:any ):value|null`\n\n Insert new element before the referenced element targetKey.\n If reference is null or not found, new element is inserted at the end\n of the list.\n \n *return* Value for key or null if !key or key always used.\n\n\n* `set( key:string, value:any ) : oldValue|null`\n* `setAt( index:number, value:any ) : oldValue|null`\n \n Overwrite the value for the given key/index.\n \n *return* The old value or null, if key/index not found.\n\n* `move( key:string, targetKey:string ) : value|null`\n* `moveAt( index:number, targetIndex:number ) : value|null`\n \n Move the key to position of targetKey by inserting key before targetKey.\n If targetKey is not found, key will be moved to the end.\n \n *return* Value for key or null if key was not found.\n\n* `remove( key:string ) : oldValue|null`\n* `removeAt( index:number ) : oldValue|null`\n \n Remove the entry for the given key.\n \n *return* The old value or null, if key was not found.\n\n### next, previous\n\nThe IndexedMap do not have a current element. To get next or previous entry,\nyou need to give a reference entry to the function.\n\n* `nextKeyOf( key:string ) : key|null`\n* `prevKeyOf( key:string ) : key|null`\n\n *return* key from entry next/previous to given key or null, if key\n has no next/previous.\n\n* `getNextOf( key:string ) : value|null`\n* `getPrevOf( key:string ) : value|null`\n \n *return* Value from entry next/previous to given key or null, if key\n has no next/previous.\n\n\n### iterating methods\n\n* `sort( [callback] )`\n \n Sort the map, that method manipulate the indexedMap.\n This function is analog to the sort function of Array.\n if no callback is specified, keys will be sorted lexicographically\n \n *params* callback {function(this:IndexedMap, valueA:any, valueB:any):number} - optional\n - called in context of indexedMap\n - compareFunction have to return _0_ for equal, _<0_ for a < b or _>0_ for a > b\n \n *return* The indexedMap\n\n* `find(callback [, startIndex])`\n \n Returns the first key, where callback function returns true.\n\n *param* {function(this:IndexedMap, key:string, value:any):boolean} callback - required\n - called for every entry in context of indexedMap\n - return true will stop the search and return the value of current visited entry.\n \n *param* {number} startIndex - optional\n Position to start the search, default is 0.\n \n *return* Value of first entry found or null, if nothing found\n\n* `each(callback [, startIndex])`\n\n Iterate over the indexedMap. Start at given startIndex. Run until end\n or the given callback returns 'false'.\n\n *param* {function(this:IndexedMap, key:string, value:any):boolean} callback - required\n - called for every entry in context of current IndexedMap\n - stop loop from within the callback function by returning false\n \n *param* {number} startIndex - optional\n position to start the run, default: 0\n \n *return* Zhe indexedMap or null for error (missing callback).\n\n\n## Test\n\n```bash\ncd <IndexedMapDir>\nnpm install .\nnpm test\n```\n\n## License\n\nThe MIT License\n\nCopyright (c) 2012-2013 Tobias Lindig\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",readmeFilename:"package/README.md"}},{}],"indexed-map":[function(require,module,exports){exports=module.exports=require("./lib/indexedMap.js");exports.version=require("./package").version},{"./lib/indexedMap.js":1,"./package":2}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks["$"+event]=this._callbacks["$"+event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){function on(){this.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks["$"+event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks["$"+event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks["$"+event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks["$"+event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],2:[function(require,module,exports){module.exports=function(obj,fn,scope){scope=scope||this;if(obj instanceof Array)array(obj,fn,scope);else object(obj,fn,scope)};exports.array=array;function object(obj,fn,scope){for(var i in obj){if(obj.hasOwnProperty(i)){fn.call(scope,i,obj[i])}}}function array(obj,fn,scope){for(var i=0,l=obj.length;i<l;i++){fn.call(scope,i,obj[i])}}},{}],3:[function(require,module,exports){var loop=require("looping");module.exports=function(fn){var many=function(str,obj){if(typeof str==="object")loop(str,many,this);else fn.apply(this,arguments);return this};return many}},{looping:2}],4:[function(require,module,exports){module.exports=function(obj){if(obj instanceof Array)return obj.slice(0);return clone(obj)};function clone(obj){if(typeof obj==="object"){var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy}return obj}},{}],datastore:[function(require,module,exports){var Emitter=require("component-emitter");var clone=require("shallow");var each=require("looping");var many=require("many");module.exports=Store;function Store(data){if(data instanceof Store)return data;this.data=data||{};this.formatters={}}Emitter(Store.prototype);Store.prototype.set=many(function(name,value,strict){var prev=this.data[name];if(prev!==value){this.data[name]=value;if(!strict)this.emit("updated",name,value);this.emit("change",name,value,prev);this.emit("change "+name,value,prev)}});Store.prototype.get=function(name){var formatter=this.formatters[name];var value=this.data[name];if(formatter){value=formatter[0].call(formatter[1],value)}return value};Store.prototype.has=function(name){return this.data.hasOwnProperty(name)};Store.prototype.del=function(name,strict){if(this.has(name)){if(this.data instanceof Array){this.data.splice(name,1)}else{delete this.data[name]}if(!strict)this.emit("updated",name);this.emit("deleted",name,name);this.emit("deleted "+name,name)}return this};Store.prototype.format=function(name,callback,scope){this.formatters[name]=[callback,scope];return this};Store.prototype.compute=function(name,callback){var str=callback.toString();var attrs=str.match(/this.[a-zA-Z0-9]*/g);this.set(name,callback.call(this.data));for(var l=attrs.length;l--;){this.on("change "+attrs[l].slice(5),function(){this.set(name,callback.call(this.data))})}return this};Store.prototype.reset=function(data,strict){var copy=clone(this.data);var length=data.length;this.data=data;each(copy,function(key,val){if(typeof data[key]==="undefined"){if(!strict)this.emit("updated",key);this.emit("deleted",key,length);this.emit("deleted "+key,length)}},this);each(data,function(key,val){var prev=copy[key];if(prev!==val){if(!strict)this.emit("updated",key,val);this.emit("change",key,val,prev);this.emit("change "+key,val,prev)}},this);return this};Store.prototype.loop=function(cb,scope){each(this.data,cb,scope||this);return this};Store.prototype.pipe=function(store){store.set(this.data);this.on("updated",function(name,val){if(val)return store.set(name,val);store.del(name)});return this};Store.prototype.use=function(fn){var args=[].slice.call(arguments,1);fn.apply(this,[this].concat(args));return this};Store.prototype.toJSON=function(replacer,space){return JSON.stringify(this.data,replacer,space)}},{"component-emitter":1,looping:2,many:3,shallow:4}]},{},[]);var Map=require("indexed-map");var Store=require("datastore");var rooms=Map();var keys=Map();var equipment=Map();var equipmentSpecs=Map();rooms.insert("keys",keys);rooms.insert("equipment",equipment);equipment.insert("specs",equipmentSpecs);function Resource(map){var resources={},self=this;map=map||Map();map.each(function(key){resources[key]=function(){console.log("Retrieving: ",key);console.log("For ID: ",self._id)}});this._map=map;this._resources=resources}Resource.prototype.id=function(id){this._id=id;return this._resources};var Rooms=new Resource(rooms);console.log(Rooms.id(5).equipment());console.log(Rooms.id(2).keys());
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"indexed-map": "1.0.0",
"datastore": "1.1.1"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment