Created
December 23, 2015 21:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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