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