All files nodeHierarchy.js

100% Statements 28/28
86.66% Branches 13/15
100% Functions 2/2
100% Lines 28/28

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 293x 12x 12x 12x 12x 12x 12x 12x 12x 24x 24x 24x 19x 19x 19x 24x 24x 5x 5x 19x 19x 19x 19x 24x 12x 12x 12x 12x  
export function sortNodesForParentOrder(nodes) {
  const list = Array.isArray(nodes) ? nodes.filter(Boolean) : [];
  const entries = list.map((node) => ({ id: String(node.id), node }));
  const byId = new Map(entries.map((entry) => [entry.id, entry]));
  const visiting = new Set();
  const visited = new Set();
  const ordered = [];
 
  function visit(entry) {
    if (!entry) return;
    const { id, node } = entry;
    if (visited.has(id) || visiting.has(id)) return;
 
    visiting.add(id);
 
    const parentId = node?.parentId ? String(node.parentId) : null;
    if (parentId) {
      visit(byId.get(parentId));
    }
 
    visiting.delete(id);
    visited.add(id);
    ordered.push(node);
  }
 
  entries.forEach((entry) => visit(entry));
  return ordered;
}