I have a list of elements where I need to figure out the dependency.
I have:
[{
"a": ["b", "d"]
}, {
"d": ["c", "e"]
}]
a is depending on b and d, and d on c and e. Is there a way to construct the dependencies in a clever way for this? The output should (could) be:
["b", "c", "e", "d", "a"]
/Kristian
Assuming you wanted the list of recursive dependencies of an element, including the element itself, in any order:
“for every dependency, add its dependencies to the dependency list” is clever enough?
If you want the element itself at the end rather than the beginning, you can fix that with
output.push(output.shift())If you want your dependencies in such an order that every element precedes the elements that depend on it, then you’ll have to define how to handle circular dependencies. One way to handle that is detect a circular dependency and fail.
If every dependency is needed by at most one element, then you can use the previous algorithm: simply read the output backwards (or reverse the array or use
unshiftinstead ofpush(warning: performance drop))The dependencies form a graph, and you are looking for its topological sort. One (inefficent) way would be to order the nodes in depth-first order and reinsert them if they are reentered. You could use the Open stack to detect errors – if a child is reentered from its parent, then you have a circular dependency.
A better solution would be to use the standard topological sort algorithm: While there are unsorted nodes, pick one that has no unresolved dependencies:
fiddle: http://jsfiddle.net/Xq5dz/4/