0.0.1 • Published 3 months ago

@yogln/tree-traverser v0.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
3 months ago

下载

npm install @yogln/tree-traverser -D

使用方式

const treeData = {
  value: 1,
  children: [
    {
      value: 2,
      children: [
        {value: 4, children: []},
        {value: 5, children: []},
      ],
    },
    {
      value: 3,
      children: [
        {value: 6, children: []},
        {value: 7, children: []},
        // { value: 8, children: [
        //     { value: 9, children: [] },
        // ] },
      ],
    },
  ],
};

traverseTree(treeData, (node, ctx) => {}, (options = {}));

ctx

SyntaxDescription
depth层级
index索引
parent父节点
parents父节点列表
remove移除节点
replace替换节点
break停止遍历
skip跳过本次遍历
traverseTree(
  treeData,
  (node, ctx) => {
    console.log(`Depth: ${ctx.depth}, Index: ${ctx.index}, Value: ${node.value}, ====before====`);
    // if (node.value === 5) {
    //     ctx.break(); // Stop traversing the tree
    // }
    if (node.value === 4) {
      return ctx.skip();
      // return ctx.break();
    }
    console.log(`Depth: ${ctx.depth}, Index: ${ctx.index}, Value: ${node.value}, ====after====`);
    // if (node.value === 6) {
    //     // ctx.break(); // Stop traversing the tree
    //     ctx.replace({
    //         value: 60,
    //     })
    // }
    // if (node.value === 5) {
    //     ctx.remove(); // Remove the node with value 5
    // }
  },
  {
    // order: 'post'
    // order: 'pre'
    order: 'bfs',
  }
);

options

SyntaxDescription
pre默认,前序遍历
post后序遍历
bfs层序遍历
0.0.1

3 months ago