Created
October 27, 2014 14:33
-
-
Save atlefren/716bfe3414cdf0107f0d to your computer and use it in GitHub Desktop.
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
/* 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was super helpful. Thanks!