All files / json-crdt/model/api find.ts

93.54% Statements 29/31
83.33% Branches 10/12
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 31156x 156x     156x 7047x 7047x 7047x 7047x 6864x 6864x 7056x 7056x 7056x 7055x 6972x 6972x 6968x 83x 69x 69x 69x 14x 14x 14x 14x     6859x    
import {type Path, toPath} from '@jsonjoy.com/json-pointer';
import {VecNode, ObjNode, ArrNode} from '../../nodes';
import type {JsonNode} from '../../nodes';
 
export const find = (startNode: JsonNode, path: string | Path): JsonNode => {
  const steps = toPath(path);
  let node: JsonNode | undefined = 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)) as JsonNode | undefined;
      if (!nextNode) throw new Error('NOT_FOUND');
      node = nextNode;
    } else if (node instanceof ArrNode) {
      const nextNode = node.getNode(Number(step));
      Iif (!nextNode) throw new Error('NOT_FOUND');
      node = nextNode;
    } else if (node instanceof VecNode) {
      const nextNode = node.get(Number(step)) as JsonNode | undefined;
      Iif (!nextNode) throw new Error('NOT_FOUND');
      node = nextNode;
    }
  }
  return node;
};