Last active
October 22, 2023 05:38
-
-
Save RoyalIcing/f814dbb919e627b230c017053ba358a9 to your computer and use it in GitHub Desktop.
Map with Fallback: https://twitter.com/andrewingram/status/1715809443097563634
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 undefinedValue = Symbol(); | |
export class MapWithFallback<Key, Value> { | |
#map: Map<Key, Value>; | |
#fallback: Value; | |
constructor(fallback: Value) { | |
this.#map = new Map(); | |
this.#fallback = fallback; | |
} | |
get(key: Key): Value { | |
const value = this.#map.get(key); | |
if (value === undefined) return this.#fallback; | |
if (value === undefinedValue) return undefined; | |
return value; | |
} | |
set(key: Key, value: Value) { | |
if (value === undefined) { | |
value = undefinedValue; | |
} | |
this.#map.set(key, value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment