function dep_tree(graph,node,prev_deps){
return uniq(flatten(graph[node].map(function(child_node){
if (contains(prev_deps,child_node))
throw "Circular reference between "+child_node+" and "+node;
return dep_tree(graph,child_node,prev_deps ? prev_deps.concat(node) : [node])
})).concat(node));
};
graph
is an object such as{a:[],b:["a"],c:[],d:["b","c"]}
, that links a file, ex:"d"
to it's dependencies"b" "c"
.file
is the the node to search.prev_deps
is internal, to keep track of visited nodes
The function returns the full dependency tree of that node. For example, dep_tree(that_obj_above,"d") = ["b","c","a"]
. Is this code correct, overall? Is it correctly checking for circular dependencies? Is there a name for what I'm doing?
1 Answer 1
Not a lot of code to review,
- To reduce confusion, I would use
_.uniq()
rather than point straight touniq()
- lowerCamelCase is preferred,
child_node
->childNode
dep_tree
is unfortunate, I likerecursiveDependencies
betterI would have set
prev_deps = prev_deps || [];
prior to return, it would make your recursive call less golfic:return dep_tree(graph,child_node, prev_deps.concat(node) )
Explore related questions
See similar questions with these tags.
uniq
,flatten
are imported fromunderscore.js
? \$\endgroup\$