Skip to content

Instantly share code, notes, and snippets.

@atlefren
Created October 27, 2014 14:33
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atlefren/716bfe3414cdf0107f0d to your computer and use it in GitHub Desktop.
Save atlefren/716bfe3414cdf0107f0d to your computer and use it in GitHub Desktop.
/* Kinda like Python's defaultdict, but for JS*/
function defDict(type) {
var dict = {};
return {
get: function (key) {
if (!dict[key]) {
dict[key] = type.constructor();
}
return dict[key];
},
dict: dict
};
}
/* Usage*/
var a = defDict([]);
a.get('a').push(1);
a.get('a').push(2);
a.get('b').push(3);
console.log(a.dict)
@taarushv
Copy link

This was super helpful. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment