Skip to content

Instantly share code, notes, and snippets.

@maxnachlinger
Last active February 6, 2021 20:32
Show Gist options
  • Save maxnachlinger/666c67e37a6baa4fdc4818ab6d652756 to your computer and use it in GitHub Desktop.
Save maxnachlinger/666c67e37a6baa4fdc4818ab6d652756 to your computer and use it in GitHub Desktop.
const baseTree = {
id: 'root',
children: [
{
id: 'child0',
children: [
{
id: 'child0-0',
children: [
{
id: 'child0-0-0',
children: [
{
id: 'child0-0-0-0',
children: [
{
id: 'child0-0-0-0',
children: null,
},
],
},
],
},
{
id: 'child0-0-1',
children: null,
},
],
},
],
},
{
id: 'child1',
children: [
{
id: 'child1-0',
children: null,
},
],
},
],
};
const iterationDfsGetIds = (tree) => {
const stack = [tree];
const result = [];
while (stack.length > 0) {
const { id, children } = stack.pop();
result.push(id);
if (children) {
stack.push(...children);
}
}
return result;
};
/*
Don't use this. Really. :) JavaScript does not perform tail recursion optimization,
so if your recursion is too deep, you may get a call stack overflow.
*/
const recursionDfsGetIds = (tree) => {
const result = [tree.id];
if (tree.children) {
result.push(...tree.children.map((node) => recursionDfsGetIds(node)).flat());
}
return result;
};
const iterationBfsGetIds = (tree) => {
const queue = [tree];
const result = [];
while (queue.length > 0) {
const { id, children } = queue.shift();
result.push(id);
if (children) {
queue.push(...children);
}
}
return result;
};
const addParentIds = (tree) => {
const newTree = JSON.parse(JSON.stringify(tree));
// root node
newTree.parentId = null;
const queue = [newTree];
while (queue.length > 0) {
const node = queue.shift();
if (node.children) {
queue.push(
...node.children.map((child) => {
// mutating the reference here intentionally
child.parentId = node.id;
return child;
}),
);
}
}
return newTree;
};
console.log('iterationDfsGetIds', iterationDfsGetIds(baseTree));
console.log('recursionDfsGetIds', recursionDfsGetIds(baseTree));
console.log('iterationBfsGetIds', iterationBfsGetIds(baseTree));
console.log('addParentIds', JSON.stringify(addParentIds(baseTree), null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment