All files / src/utils traverse.ts

100% Statements 22/22
100% Branches 5/5
100% Functions 3/3
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48    5x           6x 22x 22x 22x 2x   20x 20x 23x 19x 19x       4x     5x           22x 22x 2x     20x 20x 20x 16x 3x         17x    
import { ID, Node, PlainObject } from '../types';
 
export function doBFS<N extends PlainObject>(
  queue: Node<N>[],
  visited: Set<ID>,
  fn: (node: Node<N>) => boolean | void,
  navigator: (id: ID) => Node<N>[],
): boolean {
  while (queue.length) {
    const node = queue.shift()!;
    const abort = fn(node);
    if (abort) {
      return true;
    }
    visited.add(node.id);
    navigator(node.id).forEach((n) => {
      if (!visited.has(n.id)) {
        visited.add(n.id);
        queue.push(n);
      }
    });
  }
  return false;
}
 
export function doDFS<N extends PlainObject>(
  node: Node<N>,
  visited: Set<ID>,
  fn: (node: Node<N>) => boolean | void,
  navigator: (id: ID) => Node<N>[],
): boolean {
  const abort = fn(node);
  if (abort) {
    return true;
  }
 
  visited.add(node.id);
  for (const n of navigator(node.id)) {
    if (!visited.has(n.id)) {
      if (doDFS(n, visited, fn, navigator)) {
        return true;
      }
    }
  }
 
  return false;
}