UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

36 lines (35 loc) 1.11 kB
import { toPath } from '@jsonjoy.com/json-pointer'; import { VecNode, ObjNode, ArrNode } from '../../nodes'; export const find = (startNode, path) => { const steps = toPath(path); let node = startNode; const length = steps.length; if (!length) return node; let i = 0; while (i < length && node) { const step = steps[i++]; node = node.container(); if (!node) throw new Error('NOT_CONTAINER'); if (node instanceof ObjNode) { const nextNode = node.get(String(step)); if (!nextNode) throw new Error('NOT_FOUND'); node = nextNode; } else if (node instanceof ArrNode) { const nextNode = node.getNode(Number(step)); if (!nextNode) throw new Error('NOT_FOUND'); node = nextNode; } else if (node instanceof VecNode) { const nextNode = node.get(Number(step)); if (!nextNode) throw new Error('NOT_FOUND'); node = nextNode; } } return node; };