map.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. export interface DefaultMap<K, V> extends Map<K, V> {
  7. /** Return the value for `key` when available or the default value otherwise. */
  8. getDefault: (key: K) => V
  9. }
  10. /** A `Map` instance with a `getDefault` method added. */
  11. export function DefaultMap<K, V>(valueCtor: () => V) {
  12. const map = new Map<K, V>() as DefaultMap<K, V>;
  13. map.getDefault = (key: K) => {
  14. if (map.has(key)) return map.get(key)!;
  15. const value = valueCtor();
  16. map.set(key, value);
  17. return value;
  18. };
  19. return map;
  20. }
  21. // TODO currently not working, see https://github.com/Microsoft/TypeScript/issues/10853
  22. // /** A `Map` with a `getDefault` method added. */
  23. // export class DefaultMap<K, V> extends Map<K, V> {
  24. // constructor(private valueCtor: () => V, entries?: ReadonlyArray<[K, V]>) {
  25. // super(entries)
  26. // }
  27. // /** Return the value for `key` when available or the default value otherwise. */
  28. // getDefault(key: K) {
  29. // if (this.has(key)) return this.get(key)!
  30. // const value = this.valueCtor()
  31. // this.set(key, value)
  32. // return value
  33. // }
  34. // }