s-libs icon indicating copy to clipboard operation
s-libs copied to clipboard

[js-core] Feature request: `MagicalMap`

Open ersimont opened this issue 4 years ago • 0 comments

Perhaps it needs a more professional name 🙂.

export class MagicalMap<Key, Value> {
  #map = new Map<Key, Value>();

  constructor(private createNewValue: () => Value) {}

  get(key: Key): Value {
    if (this.#map.has(key)) {
      return this.#map.get(key)!;
    }

    const value = this.createNewValue();
    this.#map.set(key, value);
    return value;
  }

  keys(): Iterable<Key> {
    return this.#map.keys();
  }

  values(): Iterable<Value> {
    return this.#map.values();
  }
}

ersimont avatar Dec 18 '21 00:12 ersimont