Skip to content

Instantly share code, notes, and snippets.

@treelite
Created January 14, 2019 08:56
Show Gist options
  • Save treelite/8d32e2066a0d83fb1e694cbd4cf2b2fb to your computer and use it in GitHub Desktop.
Save treelite/8d32e2066a0d83fb1e694cbd4cf2b2fb to your computer and use it in GitHub Desktop.
Traverse children from a tree
function traverseChildren(node, fn, paths = []) {
const children = node.children || [];
let i = 0;
for (const child of children) {
const currentPaths = [...paths, i++];
let stop = fn(child, currentPaths);
if (!stop) {
stop = traverseChildren(child, fn, currentPaths);
}
if (stop) {
return true;
}
}
return false;
}
function getNodePathsByIndex(tree, index) {
let result = [];
let currentIndex = 0;
traverseChildren(tree, (node, paths) => {
if (currentIndex++ === index) {
result = paths.slice();
return true;
}
});
return result;
}
const items = {
name: "root",
children: [
{
name: "child1",
children: [
{ name: "child1-1" }, { name: "child-2" },
],
},
{
name: "child2",
},
{
name: "child3",
children: [
{ name: "child3-1" }
],
},
],
};
console.log("index 0", JSON.stringify(getNodePathsByIndex(items, 0)) === JSON.stringify([0]));
console.log("index 1", JSON.stringify(getNodePathsByIndex(items, 1)) === JSON.stringify([0, 0]));
console.log("index 2", JSON.stringify(getNodePathsByIndex(items, 2)) === JSON.stringify([0, 1]));
console.log("index 3", JSON.stringify(getNodePathsByIndex(items, 3)) === JSON.stringify([1]));
console.log("index 4", JSON.stringify(getNodePathsByIndex(items, 4)) === JSON.stringify([2]));
console.log("index 5", JSON.stringify(getNodePathsByIndex(items, 5)) === JSON.stringify([2, 0]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment