forEach
Traverse a tree and run a visitor callback on every node, an easy way to collect, log, or mutate nodes across all depths.
Usage
The forEach method traverses every node in the tree in depth-first order and executes the visitor function on each node.
example.ts
import { Tree } from '@movk/core'
const tree = [{ id: 1, name: 'A', children: [{ id: 2, name: 'B' }] }]
const names: string[] = []
Tree.forEach(tree, ({ node }) => {
names.push(node.name)
})
// names => ['A', 'B']
// Early termination
Tree.forEach(tree, ({ node }) => {
if (node.name === 'A') {
return false // stop traversal
}
})
API
forEach<T extends TreeNode>(tree: T[], visitor: (context: VisitorContext<T>) => void | false, config?: TreeConfig): void
Parameters
tree
T[] required
The source tree array.
predicate
(context: VisitorContext<T>) => boolean required
A predicate function called for each node in the tree. If the function returns
true, that node and all its ancestor nodes will be retained in the result.
The function receives a context object with the following properties:node
T
The node currently being processed.
depth
number
The depth of the node (root node is 0).
path
T[]
An array of nodes from the root to the current node (inclusive).
index
number
The index of the current node among its siblings.
config
TreeConfig
Configuration object for customizing the
id, pid, children key names in the tree structure.id
string
Optional. The key name for the node's unique identifier. Defaults to "id".
pid
string
Optional. The key name for the node's parent identifier. Defaults to "pid".
children
string
Optional. The key name for the children array. Defaults to "children".
Changelog
No recent changes