Created
February 21, 2025 13:46
-
-
Save colelawrence/85211673b5ba216ffd890b49f80d6ddc to your computer and use it in GitHub Desktop.
This file contains 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
export class MapOrSetDefault<K, T> extends Map<K, T> { | |
#setDefault(key: K): T { | |
const val = this.getDefault(key); | |
this.set(key, val); | |
return val; | |
} | |
constructor(public getDefault: (key: K) => T) { | |
super(); | |
} | |
update(key: K, from: (current: T) => T): void { | |
// biome-ignore lint/style/noNonNullAssertion: duh | |
this.set(key, from(this.has(key) ? this.get(key)! : this.getDefault(key))); | |
} | |
getOrSetDefault(key: K): T { | |
// biome-ignore lint/style/noNonNullAssertion: duh | |
return this.has(key) ? this.get(key)! : this.#setDefault(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment