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

Returns

TreeNode<T>[]
The updated new tree array; returns the original tree if no match is found.

Changelog

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