All files path.ts

86.67% Statements 13/15
75% Branches 6/8
100% Functions 3/3
92.31% Lines 12/13

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 47 48 498x 8x                                             8x 2x           2x       14x 12x   12x 12x 12x 12x         2x    
import { purry } from './purry';
import { isObject, isArray } from './guards';
 
/**
 * Gets the value at `path` of `object`
 * @param object the target object
 * @param path the path of the property to get
 * @signature
 *    P.path(object, path)
 * @signature
 *    P.path(path)(object)
 * @example
 *    P.path({x: { y: 1 }}, ['x', 'y']) // 1
 *    P.path({x: { y: 1 }}, ['y']) // undefined
 *    P.pipe({x: { y: { z: { a: [0] }} }}, P.path("x.y.z.a.0".split('.'))) // 0
 * @category Object, Pipe
 */
export function path(
  object: Record<string, unknown>,
  path: readonly string[]
): unknown;
export function path(
  path: readonly (string | number)[]
): (object: Record<string, unknown>) => unknown;
export function path() {
  return purry(_path, arguments);
}
function _path(
  obj: Record<string, unknown>,
  path: ReadonlyArray<string | number>
): unknown {
  const recursion = (
    path: ReadonlyArray<string | number>,
    _ro: unknown
  ): unknown => {
    if (path.length === 0) return _ro;
    Iif (!isObject(_ro) && !isArray(_ro)) return;
 
    const rest = path.slice(1);
    const firstSegment = path[0];
    Eif (firstSegment in _ro) {
      return recursion(rest, (_ro as any)[firstSegment]);
    }
 
    return;
  };
  return recursion(path, obj);
}