All files / src/algorithm components.ts

100% Statements 19/19
100% Branches 4/4
100% Functions 4/4
100% Lines 17/17

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    16x 4x 4x 4x   4x 11x 11x   11x 25x 25x 11x 11x 11x 11x       11x 5x       4x        
import Graph from '../Graph';
 
const components = <NodeIDType>(graph: Graph<NodeIDType>) => {
  const visited = new Set();
  const resultComponents: NodeIDType[][] = [];
  const nodes = graph.nodes();
 
  nodes.forEach((n) => {
    const componentsArr: NodeIDType[] = [];
    const waitingList = [n];
 
    while (waitingList.length > 0) {
      const node = waitingList.pop()!;
      if (!visited.has(node)) {
        visited.add(node);
        componentsArr.push(node);
        graph.successors(node)?.forEach((n) => waitingList.push(n));
        graph.predecessors(node)?.forEach((n) => waitingList.push(n));
      }
    }
 
    if (componentsArr.length) {
      resultComponents.push(componentsArr);
    }
  });
 
  return resultComponents;
};
 
export default components;