All files / object deep-merge.ts

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

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        13x 2x   11x 5x   6x   8x                                         5x    
import { isRecord } from '../guard';
import type { DeepPartial } from '../types';
 
function mergeValues(base: unknown, patch: unknown): unknown {
  if (patch === undefined) {
    return base;
  }
  if (!isRecord(base) || !isRecord(patch)) {
    return patch;
  }
  return Object.fromEntries([
    ...Object.entries(base),
    ...Object.entries(patch).map(([key, value]) => [
      key,
      mergeValues(Object.hasOwn(base, key) ? base[key] : undefined, value),
    ]),
  ]);
}
 
/**
 * Applies a partial patch to nested settings, such as saved preferences over the defaults: plain objects are
 * merged at every depth, other values replace, `undefined` keeps. A `__proto__` key stays a plain property.
 *
 * @template T - The type of the settings.
 * @param base - The complete object, such as the defaults.
 * @param patch - The values to change.
 * @returns A new object that shares the unchanged branches with `base`.
 * @example
 * deepMerge({ grid: { step: 10, isVisible: true } }, { grid: { isVisible: false } });
 * // { grid: { step: 10, isVisible: false } }
 */
export function deepMerge<T extends object>(base: T, patch: DeepPartial<NoInfer<T>>): T {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- A DeepPartial<T> merged into a T is a T.
  return mergeValues(base, patch) as T;
}