实现说明
全部逻辑都在函数 foldTree中。
使用要点
- 演示输出是带标签的(
depth-first visit order:、tree depth:、leaf count:),每个操作都会留下自己的一行标注。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 文件在加载时定义 foldTree。
核心语句
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),
);
代码示例
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);