Skip to content

Instantly share code, notes, and snippets.

@sveitser
Last active April 30, 2022 22:35
Show Gist options
  • Save sveitser/e980d9522c1a290e04007d78c2e79adb to your computer and use it in GitHub Desktop.
Save sveitser/e980d9522c1a290e04007d78c2e79adb to your computer and use it in GitHub Desktop.
Wannabe defaultdict for typescript. Not really tested.
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
}
}
}
@zimonitrome
Copy link

How should this be used?

@sveitser
Copy link
Author

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