simontonsoftware / s-libs

A collection of libraries for any of javascript, rxjs, or angular.
MIT License
43 stars 5 forks source link

[js-core] Feature request: `MagicalMap` #70

Closed ersimont closed 1 year ago

ersimont commented 2 years ago

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 commented 1 year ago

Make createNewValue accept the key, too!

ersimont commented 1 year ago

Will be in the next release