Created
July 7, 2012 23:27
-
-
Save nfeldman/3068550 to your computer and use it in GitHub Desktop.
one way to do a dictionary in ES5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// as a nodejs module | |
module.exports = makeDictionary(); | |
function makeDictionary (dict) { | |
return function Dictionary () { | |
!dict && (dict = Object.create(null)); | |
var Dictionary = { | |
__proto__: null, | |
get: function (name) { | |
return dict[name]; | |
}, | |
set: function (name, value) { | |
return dict[name] = value; | |
}, | |
each: function (callback, thisObj) { | |
var key; | |
for (key in dict) | |
callback.call(thisObj, dict[key], key) | |
}, | |
map: function (callback, thisObj) { | |
var _dict = Object.create(null), | |
key; | |
for (key in dict) | |
_dict[key] = callback.call(thisObj, dict[key], key); | |
return makeDictionary(_dict)(); | |
}, | |
filter: function (comparator, thisObj) { | |
var _dict = Object.create(null), | |
key; | |
for (key in dict) | |
callback.call(thisObj, dict[key], key) && (_dict[key] = dict[key]); | |
return makeDictionary(_dict)(); | |
} | |
}; | |
Object.freeze(Dictionary); | |
return Dictionary; | |
} | |
} | |
/* | |
// example: | |
var dict = require('dictionary'); | |
var d = dict(); | |
d.set('foo', 'bar'); | |
d.get('foo'); // 'bar' | |
d.foo = 'bar'; | |
d.foo; // undefined | |
var D = d.map(function (val) { return val.toUpperCase() }); | |
D.get('foo'); // 'BAR' | |
// having .get() and .set() annoys me, though | |
// I think harmony proxies will make it possible to write PHP style __get and __set methods? | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment