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]) 
  • 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
    \$\begingroup\$ uniq, flatten are imported from underscore.js? \$\endgroup\$ Commented Mar 23, 2013 at 8:43
  • \$\begingroup\$ @JanDvorak Yes, I forgot to mention, sorry. Do I know you? That name sounds familiar. \$\endgroup\$
    – MaiaVictor
    Commented Mar 23, 2013 at 8:51
  • \$\begingroup\$ We have met before \$\endgroup\$ Commented Mar 23, 2013 at 8:52
  • \$\begingroup\$ @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!? \$\endgroup\$
    – MaiaVictor
    Commented Mar 23, 2013 at 8:53
  • \$\begingroup\$ I don't come often to CR. I know I should. \$\endgroup\$ Commented Mar 23, 2013 at 8:55

1 Answer 1


Not a lot of code to review,

  • 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) ) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.