Created
August 28, 2013 17:48
-
-
Save elplatt/6369009 to your computer and use it in GitHub Desktop.
This JavaScript class wraps an Object to provide useful hash table / dictionary functionality. All data is maintained in the underlying Object. It doesn't pollute Object.prototype, so it plays nice with jQuery. See dict-example.js for examples.
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
map = { | |
"USA": { "Detroit": 23, "Cambridge": 5, "Cupertino": 0.5 }, | |
"Canada": { "Waterloo": 1 }, | |
"Switzerland": { "Geneva": 0.5 } | |
} | |
d = new Dict(map); | |
d.getDict("USA").get("Detroit"); // => 23 | |
d.getDict("China", {}).get("Beijing", 0); // => 0 | |
d.getDict("USA").keys() // => ["Detroit", "Cambridge", "Cupertino"] | |
d.getDict("USA").set("Cambridge", 6); | |
d.getDict("USA").get("Cambridge"); // => 6 | |
map.USA.Cambridge; // => 6 |
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
Dict = function (obj) { this.obj = obj ? obj : {}; }; | |
Dict.prototype = { | |
get: function (key, d) { | |
return typeof(this.obj[key]) === 'undefined' ? d : this.obj[key]; | |
}, | |
getDict: function (key, d) { | |
result = typeof(this.obj[key]) === 'undefined' ? d : this.obj[key]; | |
return new Dict(result); | |
}, | |
set: function (key, value) { this.obj[key] = value; }, | |
map: function (f) { | |
if (typeof(f) !== 'function') { return []; } | |
result = []; | |
for (key in this.obj) { | |
if (this.obj.hasOwnProperty(key)) { | |
result.push(f(key, this.obj[key])); | |
} | |
} | |
return result; | |
}, | |
keys: function () { return this.map(function (k, v) { return k; }); }, | |
values: function () { return this.map(function (k, v) { return v; }); } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment