# Is this code for getting the dependency tree of a file correct?

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?

• uniq, flatten are imported from underscore.js? – John Dvorak Mar 23 '13 at 8:43
• @JanDvorak Yes, I forgot to mention, sorry. Do I know you? That name sounds familiar. – MaiaVictor Mar 23 '13 at 8:51
• We have met before – John Dvorak Mar 23 '13 at 8:52
• @JanDvorak Oh sure you're the guy who made my fuzzy_match faster than assembly, thanks for that! Actually that was your only answer...!? Why!? – MaiaVictor Mar 23 '13 at 8:53
• I don't come often to CR. I know I should. – John Dvorak Mar 23 '13 at 8:55

• To reduce confusion, I would use _.uniq() rather than point straight to uniq()
• lowerCamelCase is preferred, child_node -> childNode
• dep_tree is unfortunate, I like recursiveDependencies better
• I 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) )