tree-return
v1.0.5
Published
walk a tree and return something, like Array.prototype.map.
Downloads
3
Readme
tree-return
walk a tree/forest and return something, like Array.prototype.map.
function treeMap(
tree: any[] | Record<any, any>,
handler: (node: any[], index: number, parent: any) => any,
isSpread = true,
customKey?: Partial<
Record<"retKey" | "childrenKey" | "retChildrenKey", string>
>
)
How to use
Basic usage: walk a tree and return a forest.
import { treeMap } from "treeReturn";
const tree = {
value: "father",
children: [
{
value: "child1",
children: [],
},
{
value: "child2",
children: [],
},
],
};
const res = treeMap(tree, (currentNode, index, parent) => {
return {
value: currentNode.value,
parentValue: parent?.value,
};
});
console.log(res);
// [{
// value: "father",
// parentValue: undefined,
// children: [
// {
// value: "child1",
// parentValue: "father",
// children: [],
// },
// {
// value: "child2",
// parentValue: "father",
// children: [],
// },
// ],
// }];
The method always returns a array which we call it forest.
Walk a forest.
const forest = [
{
value: "father",
children: [
{
value: "child1",
children: [],
},
{
value: "child2",
children: [],
},
],
},
{
value: "father2",
children: [
{
value: "child3",
children: [],
},
{
value: "child4",
children: [],
},
],
},
];
treeMap(forest, () => {
// do and return something
});
Add or remove a node.
// return an array to add.
treeMap(forest, currentNode => {
return currentNode.value === "father2"
? [
currentNode,
{
value: "extra parent",
},
]
: currentNode;
});
// return an empty array to remove
treeMap(forest, currentNode => {
return currentNode.value === "father2" ? [] : currentNode;
});
The array you return will speared by default, you can pass false
to the third argument to prevent it.
Custom key.
If your children key is child
instead of children
, you can pass the fourth argument.
treeMap(
forest,
() => {
// do and return something
},
true,
{
childrenKey: "child",
}
);