All files / map/src replace.ts

100% Statements 6/6
100% Branches 5/5
100% Functions 3/3
100% Lines 6/6

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                                                        5x           1x 5x 5x 3x     2x    
/**
 * Override a {@link Map} entry if an entry with the same key exists.
 *
 * An optional `oldValue` can be provided, which has to match the current
 * value inside the {@link Map}.
 *
 * @mutation
 *
 * @example
 * Override value if key exists
 * ```ts
 * const map = new Map([[1, 2]]);
 * replace(map)(1, 3);
 * console.log(map); // Map([[1, 3]])
 * ```
 *
 * @example
 * Override value if current value matches old value
 * ```ts
 * const map = new Map([[1, 2]]);
 * replace(map)(1, 2, 3);
 * console.log(map); // Map([[1, 3]])
 * ```
 *
 * @typeParam K - the {@link Map} key type
 * @typeParam V - the {@link Map} value type
 * @param map - the {@link Map} to set the entry
 */
export const replace: {
  <K, V>(map: Map<K, V>): {
    (key: K, value: V): void;
    (key: K, oldValue: V, newValue: V): void;
  };
} =
  (map) =>
  (key, value, value2: typeof value = value): void => {
    if ((value !== value2 && value !== map.get(key)) || !map.has(key)) {
      return;
    }
 
    map.set(key, value2);
  };