Skip to content

Instantly share code, notes, and snippets.

@damirm
Created June 7, 2017 09:23
Show Gist options
  • Save damirm/a2a2fdc30940f5dcb2ba085e10468f05 to your computer and use it in GitHub Desktop.
Save damirm/a2a2fdc30940f5dcb2ba085e10468f05 to your computer and use it in GitHub Desktop.
'use strict';
function damir(tree, dest) {
if (tree.name === dest) {
return [tree.name];
}
for (let i = 0; i < tree.children.length; ++i) {
const result = [tree.name];
const item = tree.children[i];
if (item.name === dest) {
return result.concat(item.name);
} else if (Array.isArray(item.children)) {
const found = damir(item, dest);
if (found) {
return result.concat(found);
}
}
}
}
function damir2(tree, dest) {
const result = [tree.name];
if (tree.name === dest) {
return result;
}
for (let i = 0; i < tree.children.length; ++i) {
const found = damir2(tree.children[i], dest);
if (found) {
return result.concat(found);
}
}
}
function rewle(tree, name) {
var workers = [{
node: tree,
path: [tree.name]
}];
while (workers.length) {
var worker = workers.shift();
if (worker.node.name === name) {
return worker.path;
}
worker.node.children.forEach((node, i) => {
workers.push({
node: node,
path: worker.path.concat(node.name)
})
});
}
}
function test(name, fn, iters, ...args) {
console.time(name);
for (let i = 0; i < iters; ++i) {
fn.apply(null, args);
}
console.timeEnd(name);
console.log(`Result of ${name}:`, fn.apply(null, args));
}
const TREE = {
name: 1,
children: [
{
name: 2,
children: []
},
{
name: 3,
children: [
{
name: 4,
children: []
},
{
name: 5,
children: [
{
name: 6,
children: []
}
]
}
]
}
]
};
const ITERS = 100000;
const DEST = 6;
test('damir', damir, ITERS, TREE, DEST);
test('damir2', damir2, ITERS, TREE, DEST);
test('rewle', rewle, ITERS, TREE, DEST);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment