Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Last active October 22, 2023 05:38
Show Gist options
  • Save RoyalIcing/f814dbb919e627b230c017053ba358a9 to your computer and use it in GitHub Desktop.
Save RoyalIcing/f814dbb919e627b230c017053ba358a9 to your computer and use it in GitHub Desktop.
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