Skip to content

Instantly share code, notes, and snippets.

@thomaswilburn
Created December 12, 2023 22:35
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 thomaswilburn/c485f5b1ee116ec1c491b1bea07308ce to your computer and use it in GitHub Desktop.
Save thomaswilburn/c485f5b1ee116ec1c491b1bea07308ce to your computer and use it in GitHub Desktop.
Defaultdict but make it JavaScript
const TARGET = Symbol("proxy target");
function defaultdict(missing) {
var dict = {};
var instantiate = missing;
if (missing instanceof Function) {
if (missing.constructor) {
instantiate = () => new missing();
}
} else if (missing instanceof Object) {
instantiate = () => structuredClone(missing);
} else {
instantiate = () => missing;
}
var proxy = new Proxy(dict, {
get(target, key) {
if (key == TARGET) return target;
return target[key] ??= instantiate();
}
});
return proxy;
}
var counter = defaultdict(0);
"abccdddddeedfab".split("").forEach(l => counter[l]++);
console.log(counter[TARGET]);
var countunique = defaultdict(Set);
countunique["AZ"].add(2022);
countunique["TX"].add(2023);
countunique["AZ"].add(2023);
console.log(countunique[TARGET]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment