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

96.66% Statements 29/30
93.33% Branches 14/15
100% Functions 1/1
100% Lines 25/25

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    1x   1x   1x   1x 12x     10x 10x 10x 22x 22x 22x 22x 22x 5x 5x   4x 4x 4x 4x   4x 17x 16x 16x 1x   8x    
/* tslint:disable no-string-throw */
 
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);
    key = indexOfSlash > -1 ? pointer.substring(indexAfterSlash, indexOfSlash) : pointer.substring(indexAfterSlash);
    indexAfterSlash = indexOfSlash + 1;
    obj = val;
    if (isArray(obj)) {
      const length = obj.length;
      if (key === '-') key = length;
      else {
        const key2 = ~~key;
        Iif ('' + key2 !== key) throw new Error('INVALID_INDEX');
        key = key2;
        if (key < 0) throw 'INVALID_INDEX';
      }
      val = obj[key];
    } else if (typeof obj === 'object' && !!obj) {
      key = unescapeComponent(key);
      val = has(obj, key) ? (obj as any)[key] : undefined;
    } else throw 'NOT_FOUND';
  }
  return {val, obj, key};
};