Recursive Tree Type With Depth First Fold

Define recursive tree types where children use the node type itself, then fold every subtree with one generic combine function instead of ad hoc loops.

TypescriptData Integrity

Code

typescriptsnippet
46 lines
interface CategoryNode {
  name: string;
  children: CategoryNode[]; // recursive: the node type references itself
}

const tree: CategoryNode = {
  name: 'catalog',
  children: [
    {
      name: 'electronics',
      children: [
        { name: 'laptops', children: [] },
        { name: 'phones', children: [] },
      ],
    },
    { name: 'books', children: [] },
  ],
};

// Depth-first fold: recurse into children first, then combine the
// child results with this node's own name
function foldTree<T>(
  node: CategoryNode,
  combine: (name: string, childResults: T[]) => T,
): T {
  return combine(
    node.name,
    node.children.map((child) => foldTree(child, combine)),
  );
}

const names = foldTree<string[]>(tree, (name, childPaths) => [
  name,
  ...childPaths.flat(),
]);
console.log('depth-first visit order:', names);

const depth = foldTree<number>(tree, (_name, childDepths) =>
  childDepths.length === 0 ? 1 : 1 + Math.max(...childDepths),
);
console.log('tree depth:', depth);

const leaves = foldTree<number>(tree, (_name, childCounts) =>
  childCounts.length === 0 ? 1 : childCounts.reduce((a, b) => a + b, 0),
);
console.log('leaf count:', leaves);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

depth-first visit order: [ 'catalog', 'electronics', 'laptops', 'phones', 'books' ]
tree depth: 3
leaf count: 3

Inside the snippet

Recursive Tree Type With Depth First Fold comes down to the function foldTree.

Putting it to use

The demo output is labeled (depth-first visit order:, tree depth:, leaf count:); each label names the call that printed it.

Core lines

const names = foldTree<string[]>(tree, (name, childPaths) => [
  name,
  ...childPaths.flat(),
]);
const leaves = foldTree<number>(tree, (_name, childCounts) =>
  childCounts.length === 0 ? 1 : childCounts.reduce((a, b) => a + b, 0),
);
const depth = foldTree<number>(tree, (_name, childDepths) =>
  childDepths.length === 0 ? 1 : 1 + Math.max(...childDepths),
);

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `foldTree` at load time.