@aardpro/tree
v1.0.0
Published
把包含父指针属性的平坦数组与嵌套结构的树形数组进行互相转化的函数库。 A function library that converts a flat array with parent pointer attributes into a nested array and vice versa.
Readme
@aardpro/tree
类型导出 Types
export type TreeNode = Record<string, unknown>;
export type TreeNodes = TreeNode[];
export type PointerNode = Record<string, unknown>;
export type PointerNodes = PointerNode[];
export type WalkTreeCallback<T extends object> = (
node: T,
controller: AbortController,
level: number
) => Promise<void> | void;说明:
TreeNode/TreeNodes用于表示嵌套树形结构的数据;PointerNode/PointerNodes用于表示带父指针的平坦数组;WalkTreeCallback为遍历回调的类型,包含节点、可中止控制器与层级。
安装 Installation
pnpm
pnpm i @aardpro/tree
npm
npm i @aardpro/tree
yarn
yarn add @aardpro/tree
使用 Usage
walk 遍历函数
declare function walk<T extends object>(
treeArr: T[],
childProperty: string,
callback: WalkTreeCallback<T>
): Promise<void>;import { walk } from "@aardpro/tree";
const rawData = [
{
id: 99,
name: "root",
children: [
{
id: 88,
name: "child1",
children: [
{
id: 77,
name: "child2",
children: [
{
id: 3,
name: "child3",
},
],
},
],
},
],
},
];
// 使用同步回调
walk(rawData, "children", (node, ctrl) => {
if (node.id === 3) {
console.log("we found it:", node);
ctrl.abort();
}
});
// 使用异步回调, 等待遍历结果
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
console.log("start walk --------------");
await walk(rawData, "children", async (node, ctrl) => {
if (node.id === 77) {
await sleep(1000);
console.log("we found it: ", node);
ctrl.abort();
}
});
console.log("-------------- walk end");
}flatten 扁平化函数
declare function flatten<T extends PointerNodes>(
treeArr1: T[],
id?: string,
pid?: string,
childProperty?: string
): Promise<T[]>;import { flatten } from "@aardpro/tree";
const flatData = await flatten(rawData, 'id', 'pid', 'children')tree 做树函数
把带有父指针的平坦数组转化为嵌套数组
convert a array with all elements including pointer to parent into nesting tree array
declare function tree<T extends PointerNodes>(
flatArr1: T[],
id?: string,
pid?: string,
childProperty?: string
): T[];import { tree } from "@aardpro/tree";
const flatData = [
{
value: 99,
name: "root",
parent: null,
},
{
value: 88,
name: "child1",
parent: 99,
},
{
value: 77,
name: "child2",
parent: 88,
},
{
value: 3,
name: "child3",
parent: 77,
},
];
const treeData = tree(flatData, "value", "parent", "children");说明:
- 根节点判定:当元素的
pid为非真值(例如null、undefined、0、""、false等)时,将其视为根节点。 flatten在缺少id时会生成一个 ID;在缺少pid时会设置为null并为其子节点补齐父指针。
version logs
- 1.1.0 type WalkTreeCallback has changed
# now { node: TreeNode, controller: AbortController, level: number }
