Created
December 12, 2023 22:35
-
-
Save thomaswilburn/c485f5b1ee116ec1c491b1bea07308ce to your computer and use it in GitHub Desktop.
Defaultdict but make it JavaScript
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
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