vmo-tree v0.0.0-beta.1
VmoTree
VmoTree 是一个用于操作树形数据结构的 TypeScript
工具类,扩展了 JavaScript 的内置 Array,提供了一系列便捷的方法来处理树形结构数据。
设计特点
继承增强:TreeArray 继承了 JavaScript 原生 Array 类型,直接利用数组的能力,扩展了适合树形数据的操作方法。\ 类型安全:充分利用 TypeScript 的强类型系统,确保操作的安全性和代码的可维护性。\ 灵活易用:通过自定义节点、父节点、子节点的键名,适配不同的树形数据结构。\ 功能丰富:提供查找(find)、映射(map)、过滤(filter)、路径查找(path)、结构转换等多种实用功能。
安装
npm install VmoTree
使用范例
初始化树结构
import { VmoTree } from 'vmo-tree'
const flatData = [
{ id: 1, name: 'Root', parentId: null },
{ id: 2, name: 'Child 1', parentId: 1 },
{ id: 3, name: 'Child 2', parentId: 1 }
]
// 转换平面结构成树
// const tree = new VmoTree(flatData, { childrenKey: 'kids', parentKey: 'parentId', nodeKey: 'id' })
const tree = VmoTree.array2Tree(flatData)
console.log(tree)
使用实例方法
// 查找节点
const foundNode = tree.find(node => node.name === 'Child 1')
// 映射操作
const mappedTree = tree.map(node => ({ ...node, name: node.name.toUpperCase() }))
// 过滤操作
const filteredTree = tree.filter(node => node.name.includes('Child'))
// 查找路径
const pathToRoot = tree.path(foundNode)
console.log(pathToRoot)
使用静态方法
// 将树结构转换回数组
const flatArray = VmoTree.pluck2Array(tree)
console.log(flatArray)
API 详细说明
API 详细说明
静态方法
array2Tree(array, nodeKey, parentKey, childrenKey): 将平面数组转化为树形结构。
- 参数:
array
: 节点数组nodeKey
: 节点标识键(默认'id'
)parentKey
: 父节点标识键(默认'parentId'
)childrenKey
: 子节点集合键(默认'children'
)
- 参数:
pluck2Array(tree, nodeKey, parentKey, childrenKey): 将树结构转化为平面数组。
find(targetNode, targetTree, childrenKey, pickFirst): 查找符合条件的第一个或所有节点。
filter(predicate, targetTree, childrenKey): 过滤树中的节点,返回符合条件的树。
path(targetNode, targetTree, childrenKey, pickFirst): 找出从指定节点到根节点的路径。
map(visit, targetTree, childrenKey): 对树进行递归映射。
fromArray(array, option): 从数组创建一个
Trex
实例。
实例方法
- find(target, option): 在树中查找符合条件的节点。
map(visit, childrenKey): 对树结构应用映射函数。
filter(predicate, childrenKey): 过滤树中不符合条件的节点。
path(targetNode, option): 获取从指定节点到树根的路径。
- pluck(option): 将树结构展平为数组。
注意事项
- 性能:对于非常大型的树结构,深度拷贝操作(如
clone
)可能影响性能。 - 类型定义:确保在使用回调函数时提供正确的类型定义,以充分利用 TypeScript 的静态检查能力。
许可证
MIT License
10 months ago
10 months ago