insertBefore
Insert a new node immediately before a target node in a tree by id, returning whether the insertion succeeded.
Usage
The insertBefore method inserts a new node immediately before the target node (found by id). This method mutates the tree array in place.
example.ts
import { Tree } from '@movk/core'
const tree = [{ id: 1, name: 'A' }, { id: 2, name: 'C' }]
const newNode = { id: 3, name: 'B' }
Tree.insertBefore(tree, newNode, 2)
/*
tree will be:
[{ id: 1, name: 'A' }, { id: 3, name: 'B' }, { id: 2, name: 'C' }]
*/
API
insertBefore<T extends TreeNode>(tree: T[], node: T, targetId: number | string, config?: TreeConfig): boolean
Parameters
tree
T[] required
The source tree array.
node
T required
The new node to insert.
targetId
number | string required
The ID of the target node. The new node will be inserted before this node.
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
boolean
Returns
true if the target was found and the new node was successfully inserted, otherwise false.Changelog
No recent changes