Last active
August 6, 2020 11:51
-
-
Save kiruh/34ac87b6fcb3ada01e2428501f756cb8 to your computer and use it in GitHub Desktop.
JavaScript implementation of Python's defaultdict using Proxy and Reflect
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
const defaultdict = (getDefault) => | |
new Proxy( | |
{}, | |
{ | |
get: (target, key) => { | |
if (!Reflect.has(target, key)) | |
Reflect.set( | |
target, | |
key, | |
typeof getDefault === "function" ? getDefault() : getDefault | |
); | |
return Reflect.get(target, key); | |
}, | |
} | |
); | |
export default defaultdict; |
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
import defaultdict from "./defaultdict"; | |
const dict1 = defaultdict(Number); | |
dict1.a = dict1.a + 1; | |
const dict2 = defaultdict(Array); | |
dict2.a.push("hello world"); | |
dict2.b.push("foo bar"); | |
const ejected2 = { ...dict2 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment