Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created February 21, 2025 13:46
Show Gist options
  • Save colelawrence/85211673b5ba216ffd890b49f80d6ddc to your computer and use it in GitHub Desktop.
Save colelawrence/85211673b5ba216ffd890b49f80d6ddc to your computer and use it in GitHub Desktop.
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