Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

dep-graph.coffee 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # [dep-graph](http://github.com/TrevorBurnham/dep-graph)
  2. _ = require 'underscore'
  3. class DepGraph
  4. constructor: ->
  5. # The internal representation of the dependency graph in the format
  6. # `id: [ids]`, indicating only *direct* dependencies.
  7. @map = {}
  8. # Add a direct dependency. Returns `false` if that dependency is a duplicate.
  9. add: (id, depId) ->
  10. @map[id] ?= []
  11. return false if depId in @map[id]
  12. @map[id].push depId
  13. @map[id]
  14. # Generate a list of all dependencies (direct and indirect) for the given id,
  15. # in logical order with no duplicates.
  16. getChain: (id) ->
  17. # First, get a list of all dependencies (unordered)
  18. deps = @descendantsOf id
  19. # Second, order them (using the Tarjan algorithm)
  20. chain = []
  21. visited = {}
  22. visit = (node) =>
  23. return if visited[node] or node is id
  24. visited[node] = true
  25. visit parent for parent in @parentsOf(node) when parent in deps
  26. chain.unshift node
  27. for leafNode in _.intersection(deps, @leafNodes()).reverse()
  28. visit leafNode
  29. chain
  30. leafNodes: ->
  31. allNodes = _.uniq _.flatten _.values @map
  32. node for node in allNodes when !@map[node]?.length
  33. parentsOf: (child) ->
  34. node for node in _.keys(@map) when child in @map[node]
  35. descendantsOf: (parent, descendants = [], branch = []) ->
  36. descendants.push parent
  37. branch.push parent
  38. for child in @map[parent] ? []
  39. if child in branch # cycle
  40. throw new Error("Cyclic dependency from #{parent} to #{child}")
  41. continue if child in descendants # duplicate
  42. @descendantsOf child, descendants, branch.slice(0)
  43. descendants[1..]
  44. # Export the class in Node, make it global in the browser.
  45. if module?.exports?
  46. module.exports = DepGraph
  47. else
  48. @DepGraph = DepGraph