@js-tiny/tree-walker
v0.0.2
Published
A zero-dependency, lazy tree traversal utility for JavaScript and TypeScript.
Maintainers
Readme
@js-tiny/tree-walker
零依赖、惰性求值的 JavaScript/TypeScript 树遍历工具库。
安装
npm install @js-tiny/tree-walkerTreeWalker
将任意嵌套数据结构包装为 for...of 接口。返回带有完整路径和深度信息的类型化 TreeNode 对象。
默认支持普通对象。提供自定义 getChildren 回调函数,可遍历任意树形结构。
基本用法
import { TreeWalker } from '@js-tiny/tree-walker'
const walker = new TreeWalker({
a: 1,
b: 2,
c: {
d: 3,
e: 4,
},
})
for (const node of walker) {
console.log(node)
}
// { key: 'a', value: 1, path: ['a'], depth: 0, isLeaf: true }
// { key: 'b', value: 2, path: ['b'], depth: 0, isLeaf: true }
// { key: 'c', value: { d, e }, path: ['c'], depth: 0, isLeaf: false }
// { key: 'd', value: 3, path: ['c','d'],depth: 1, isLeaf: true }
// { key: 'e', value: 4, path: ['c','e'],depth: 1, isLeaf: true }遍历策略
for...of 和 .pre() 默认使用前序 DFS。
// 前序 DFS(默认)— 父节点优先于子节点
for (const node of walker.pre()) { ... }
for (const node of walker) { ... } // 等价
// 后序 DFS — 子节点优先于父节点
for (const node of walker.post()) { ... }
// 广度优先 — 按层级遍历
for (const node of walker.bfs()) { ... }同一个实例可以多次迭代,使用不同的遍历策略:
const leaves = [...walker].filter(n => n.isLeaf).map(n => n.value)
const paths = [...walker.bfs()].map(n => n.path.join('.'))自定义 getChildren
传入 getChildren 回调函数,可以遍历任意树形结构,而不仅限于普通对象。
const categories = {
id: 1,
name: 'root',
children: [
{ id: 2, name: 'clothing' },
{ id: 3, name: 'electronics', children: [
{ id: 4, name: 'phones' },
]},
],
}
const walker = new TreeWalker(categories, {
getChildren: (node) =>
node.children?.map((child, i) => [String(i), child]) ?? null,
})
for (const node of walker) {
console.log(node.value.name, node.depth)
}
// clothing 0
// electronics 0
// phones 1选项
expandArrays
默认情况下数组被视为叶子节点。设置 expandArrays: true 后会进入数组内部遍历,以索引作为 key:
const walker = new TreeWalker({ users: [{ name: 'Alice' }] }, { expandArrays: true })
for (const node of walker) {
console.log(node.path.join('.'))
}
// users
// users.0
// users.0.name自定义 getChildren 的优先级始终高于 expandArrays。
includeRoot
默认情况下根数据本身不参与遍历,只遍历其后代节点。设置 includeRoot: true 后,根节点也会以 { key: '', value: data, path: [], depth: 0 } 的形式产出,所有后代节点整体下移一层:
const walker = new TreeWalker({ a: 1 }, { includeRoot: true })
for (const node of walker) {
console.log(node.key, node.path, node.depth)
}
// '' [] 0
// a ['a'] 1cycleDetection
默认情况下,循环引用(节点引用了自己的祖先)会无限遍历。通过 cycleDetection 可以防护:
'none'(默认):不检测,保持现有行为。'path':跳过已经出现在当前祖先路径上的子节点;不同路径上的 DAG 共享节点仍会被访问。'global':每个对象值最多访问一次(按 WeakSet 中的引用身份去重);原始值不去重。
const a = { name: 'A' }
a.children = [a]
const walker = new TreeWalker(a, {
getChildren: (node) => node.children?.map((child, i) => [String(i), child]) ?? null,
cycleDetection: 'path',
})
console.log([...walker].length)
// 1lazyPath
默认情况下 node.path 会在产出时立即构造。对于不需要每个节点路径的深层树,可以设置 lazyPath: true,改为在首次访问时构造并按节点缓存:
const walker = new TreeWalker(deepTree, { lazyPath: true })从未读取 path 的节点完全跳过路径构造;重复读取 node.path 返回同一个缓存数组。
API
new TreeWalker(data, options?)
| 参数 | 类型 | 描述 |
|---|---|---|
| data | R | 根数据值 |
| options.getChildren | GetChildren<R, N> | 可选。返回节点的 [key, child][] 对,如果为叶子节点则返回 null/undefined |
| options.expandArrays | boolean | 可选。进入数组内部遍历,以索引作为 key。默认 false(数组为叶子节点) |
| options.includeRoot | boolean | 可选。将根数据本身产出为 { key: '', path: [], depth: 0 }。默认 false |
| options.cycleDetection | 'none' \| 'global' \| 'path' | 可选。循环引用防护模式。默认 'none' |
| options.lazyPath | boolean | 可选。在首次访问时延迟构造 node.path 并按节点缓存。默认 false |
默认 getChildren 通过 Object.entries 将普通(非数组、非null)对象视为分支。其他类型 — 原始类型、数组、null — 均为叶子节点。
类型参数
TreeWalker<R, N = R> 接收根数据类型 R 与产出节点类型 N(默认为 R)。当容器类型与节点类型不同时可以同时指定两者:
type File = { type: 'file'; content: string }
type Folder = { type: 'folder'; children: Array<Folder | File> }
type Doc = { type: 'doc'; children: Array<Folder | File> }
const walker = new TreeWalker<Doc, Folder | File>(doc, {
getChildren: (node) =>
'children' in node
? node.children.map((child, i) => [String(i), child])
: null,
})
// 产出的节点类型为 TreeNode<Folder | File>TreeNode<V>
type TreeNode<V> = {
key: string // 属性名或父节点中的索引
value: V // 节点值
path: string[] // 从根节点开始的完整路径,如 ['c', 'd']
depth: number // 深度,0 = 根节点的直接子节点
isLeaf: boolean // 如果 getChildren 返回 null/undefined/[] 则为 true
}GetChildren<R, N>
type GetChildren<R, N = R> = (value: R | N) => Array<[string, N]> | null | undefinedCycleDetectionMode
type CycleDetectionMode = 'none' | 'global' | 'path'License
MIT
