Last active
May 7, 2019 19:29
-
-
Save jobelenus/c4228af7ec9c16e79329cc3cbb6f639a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Getting defaultdict from Python in JS | |
class DefaultDict extends Object { | |
constructor(defaultInit) { | |
return new Proxy({}, { | |
get: (target, name) => name in target ? | |
target[name] : | |
(target[name] = typeof defaultInit === 'function' ? | |
new defaultInit().valueOf() : | |
defaultInit) | |
}) | |
} | |
} | |
// NOTE: [] doesn't work, use Array | |
d = new DefaultDict([]) | |
d[1].push({foo: 'bar'}) | |
d['zoo'].push({one: 1}) | |
d.zoo | |
> [ { foo: 'bar' }, { one: 1 } ] | |
d[1] | |
> [ { foo: 'bar' }, { one: 1 } ] | |
s = new DefaultDict(Array) | |
s[1].push({'foo': 'bar'}) | |
s['zoo'].push({one: 1}) | |
s[1] | |
> [ { foo: 'bar' } ] | |
s.zoo | |
> [ { one: 1 } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment