All files / src/map default-map.ts

100% Statements 8/8
100% Branches 4/4
100% Functions 3/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                      7x                 17x 17x       67x 27x 27x 27x   40x        
import {noop} from '../func/noop';
 
type DefaultFunction<K, V> = (key: K) => V;
/**
 * Allows for returning generated defaults for unknown keys.
 * Useful as a quick and dirty way to cache results of functions.
 *
 * This is intended to behave similarly to the defaultdict structure in python.
 *
 * ```
 * const sqrRts =
 *     DefaultMap.usingFunction<number, number>((x) => Math.sqrt(x));
 * sqrRts.get(9); // Returns 3
 * ```
 */
export class DefaultMap<K, V> extends Map<K, V> {
  static usingFunction<K, V>(
    defaultFunction: DefaultFunction<K, V>
  ): DefaultMap<K, V> {
    return new this([], defaultFunction);
  }
 
  private readonly defaultFunction: DefaultFunction<K, V>;
 
  constructor(
    iterable: Array<[K, V]> = [],
    defaultFunction: DefaultFunction<K, V> = noop
  ) {
    super(iterable);
    this.defaultFunction = defaultFunction;
  }
 
  get(key: K): V {
    if (!this.has(key)) {
      const defaultValue = this.defaultFunction(key);
      this.set(key, defaultValue);
      return defaultValue;
    } else {
      return super.get(key) as V;
    }
  }
}