find
Find the first tree node that matches a predicate during traversal, returning the node or undefined when nothing matches.
Usage
The find method performs a depth-first search on the tree and returns the first node that satisfies the predicate function.
example.ts
import { Tree } from '@movk/core'
const tree = [{ id: 1, name: 'A', children: [{ id: 2, name: 'B' }] }]
const node = Tree.find(tree, ({ node }) => node.name === 'B')
// node => { id: 2, name: 'B' }
API
find<T extends TreeNode>(tree: T[], predicate: (context: VisitorContext<T>) => boolean, config?: TreeConfig): T | undefined
Parameters
tree
T[] required
The source tree array.
predicate
(context: VisitorContext<T>) => boolean required
A predicate function called for each node in the tree. When the function returns
true for the first node, find returns that node and stops traversal.
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".
Returns
T | undefined
Returns the first matching node, or
undefined if no match is found.Changelog
No recent changes