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:
config
TreeConfig
Configuration object for customizing the id, pid, children key names in the tree structure.

Changelog

No recent changes
Copyright © 2024 - 2026 YiXuan - MIT License