All files / json-pointer/src get.ts

91.66% Statements 22/24
81.81% Branches 9/11
100% Functions 1/1
94.44% Lines 17/18

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 251x     1x 18x   18x 16x 32x 32x 11x 3x 2x 2x 2x   10x 21x 21x 19x     13x    
import {hasOwnProperty as has} from '@jsonjoy.com/util/lib/hasOwnProperty';
import type {Path} from './types';
 
export const get = (val: unknown, path: Path): unknown | undefined => {
  const pathLength = path.length;
  let key: string | number;
  if (!pathLength) return val;
  for (let i = 0; i < pathLength; i++) {
    key = path[i];
    if (val instanceof Array) {
      if (typeof key !== 'number') {
        if (key === '-') return undefined;
        const key2 = ~~key;
        Iif ('' + key2 !== key) return undefined;
        key = key2;
      }
      val = val[key];
    } else if (typeof val === 'object') {
      if (!val || !has(val as object, key as string)) return undefined;
      val = (val as any)[key];
    } else Ereturn undefined;
  }
  return val;
};