Skip to content

Instantly share code, notes, and snippets.

@elplatt
Created August 28, 2013 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elplatt/6369009 to your computer and use it in GitHub Desktop.
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.
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
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