updateNode v1.3.1
Immutably update a tree node by id, rebuilding only the path from root to target while keeping untouched branches by reference.
Usage
updateNode locates the node where node[config.id] === targetId, replaces it with the new node returned by updater. It only rebuilds the path from the root to the target node; untouched branches retain their original references. If the target is not found, the original tree is returned unchanged.
example.ts
import { Tree } from '@movk/core'
const tree = [{ id: '1', children: [{ id: '2', name: 'old' }] }]
const next = Tree.updateNode(tree, '2', ({ node }) => ({ ...node, name: 'new' }))
// tree remains unchanged
// next[0].children[0].name === 'new'
// next[0].children[0] is a new reference; untouched sibling branches retain their original references
API
updateNode<T>(tree: TreeNode<T>[], targetId: string, updater: TreeTransformer<T, T>, config?: TreeConfig): TreeNode<T>[]
Parameters
tree
TreeNode<T>[] required
The source tree array.
targetId
string required
The ID of the target node, matched against the key specified by
config.id.updater
TreeTransformer<T, T> required
A node update function called on the matched node. Returns the replacement node.
The function receives a
context object with the following properties:node
TreeNode<T>
The matched node currently being processed.
depth
number
The depth of the node (root node is 0).
path
TreeNode<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
TreeNode<T>[]
The updated new tree array; returns the original tree if no match is found.
Changelog
No recent changes