Skip to content

Instantly share code, notes, and snippets.

@jobelenus
Last active May 7, 2019 19:29
Show Gist options
  • Save jobelenus/c4228af7ec9c16e79329cc3cbb6f639a to your computer and use it in GitHub Desktop.
Save jobelenus/c4228af7ec9c16e79329cc3cbb6f639a to your computer and use it in GitHub Desktop.
// 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