All files / json-pointer/src/findByPointer v4.ts

100% Statements 26/26
100% Branches 16/16
100% Functions 1/1
100% Lines 22/22

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 341x   1x   1x   1x 12x     10x 10x 10x 22x   22x 22x 22x 22x 22x 5x     4x 4x   4x 17x 16x 1x   8x    
import {hasOwnProperty as has} from '@jsonjoy.com/util/lib/hasOwnProperty';
import type {Reference} from '../find';
import {unescapeComponent} from '../util';
 
const {isArray} = Array;
 
export const findByPointer = (pointer: string, val: unknown): Reference => {
  if (!pointer) return {val};
  let obj: Reference['obj'];
  let key: Reference['key'];
  let indexOfSlash = 0;
  let indexAfterSlash = 1;
  while (indexOfSlash > -1) {
    indexOfSlash = pointer.indexOf('/', indexAfterSlash);
    const component: string =
      indexOfSlash > -1 ? pointer.substring(indexAfterSlash, indexOfSlash) : pointer.substring(indexAfterSlash);
    indexAfterSlash = indexOfSlash + 1;
    key = unescapeComponent(component);
    obj = val;
    if (isArray(obj)) {
      if (key === '-') key = obj.length;
      else {
        // if (!isValidIndex(key)) throw new Error('INVALID_INDEX');
        key = ~~key;
        if (key < 0) throw new Error('INVALID_INDEX');
      }
      val = has(obj, key as any) ? obj[~~key] : undefined;
    } else if (typeof obj === 'object' && !!obj) {
      val = has(obj, key) ? (obj as any)[key] : undefined;
    } else throw new Error('NOT_FOUND');
  }
  return {val, obj, key};
};