All files setPath.ts

95% Statements 19/20
83.33% Branches 10/12
100% Functions 1/1
95% Lines 19/20

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 44 45 46 478x 8x 8x                         8x         7x         7x 7x 7x 7x 21x 21x 21x 11x 11x 11x     10x 3x     10x     7x    
import { clone } from './clone';
import { isArray, isObject } from './guards';
import { type } from './type';
 
/**
 * Dynamically sets object path
 * @param target - Target object
 * @param path - Path in object
 * @param value - On final object element
 * @signature
 *    P.setPath(obj, path, value)
 * @example
 *    P.setPath({ data: {} }, "data.value.max", 100) // { data: { value: { max: 100 } } }
 * @category Object
 */
export function setPath(
  target: { [k: string]: unknown } | Array<unknown>,
  path: (string | number)[],
  value: unknown
): unknown {
  Iif (!(isObject(target) || isArray(target))) {
    throw new Error(
      `Expecting to receive object or array. But received ${type(target)}`
    );
  }
  const clonedTarget = clone(target);
  let result = clonedTarget as any;
  const clonedPath = [...path];
  while (clonedPath.length !== 0) {
    const k = clonedPath.shift();
    Eif (k != null) {
      if (result[k] == null) {
        result[k] = clonedPath.length === 0 ? value : {};
        result = result[k];
        continue;
      }
 
      if (clonedPath.length === 0) {
        result[k] = value;
      }
 
      result = result[k];
    }
  }
  return clonedTarget;
}