Skip to content

Instantly share code, notes, and snippets.

@kiruh
Last active August 6, 2020 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiruh/34ac87b6fcb3ada01e2428501f756cb8 to your computer and use it in GitHub Desktop.
Save kiruh/34ac87b6fcb3ada01e2428501f756cb8 to your computer and use it in GitHub Desktop.
JavaScript implementation of Python's defaultdict using Proxy and Reflect
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;
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