Skip to content

Instantly share code, notes, and snippets.

@danieluhl
Created December 23, 2015 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieluhl/2c16585c6190b6535a5c to your computer and use it in GitHub Desktop.
Save danieluhl/2c16585c6190b6535a5c to your computer and use it in GitHub Desktop.
Walk a graph from leaf to root and build results based on a child/parent relationship
tree = {
a: ['b', 'c', 'd'],
b: ['e', 'f'],
c: ['g', 'h'],
h: ['i', 'j', 'k'],
k: ['l'],
l: ['m', 'n']
}
var _ = require('underscore');
function walk(node, tree, result) {
if (tree[node] && tree[node].length > 0){
_.each(tree[node], function(p) {
var branch = walk(p, tree, []);
_.each(branch, function(b) {
result.push([node].concat(b));
});
});
return result;
} else {
return node;
}
}
var result = walk('a', tree, []);
result = _.map(result, function(r) {
return r.join(' => ');
});
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment