Last active
April 30, 2022 22:35
-
-
Save sveitser/e980d9522c1a290e04007d78c2e79adb to your computer and use it in GitHub Desktop.
Wannabe defaultdict for typescript. Not really tested.
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
class DefaultDict<T, Q> extends Map<T, Q> { | |
defaultFactory: () => Q | |
constructor(defaultFactory: () => Q) { | |
super() | |
this.defaultFactory = defaultFactory | |
} | |
get(name: T): Q { | |
if (this.has(name)) { | |
return super.get(name)! | |
} else { | |
const value = this.defaultFactory() | |
this.set(name, value) | |
return value | |
} | |
} | |
} |
Haven't used this in ages. IIRC the same way as Map
but it will insert and return a new entry when calling get
with a key that isn't in the map.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How should this be used?