topologicalSort.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const PERMANENT_MARKER = 2
  2. const TEMPORARY_MARKER = 1
  3. function createError(node, graph) {
  4. const er = new Error("Nondeterministic import's order")
  5. const related = graph[node]
  6. const relatedNode = related.find(
  7. relatedNode => graph[relatedNode].indexOf(node) > -1
  8. )
  9. er.nodes = [node, relatedNode]
  10. return er
  11. }
  12. function walkGraph(node, graph, state, result, strict) {
  13. if (state[node] === PERMANENT_MARKER) return
  14. if (state[node] === TEMPORARY_MARKER) {
  15. if (strict) return createError(node, graph)
  16. return
  17. }
  18. state[node] = TEMPORARY_MARKER
  19. const children = graph[node]
  20. const length = children.length
  21. for (let i = 0; i < length; ++i) {
  22. const er = walkGraph(children[i], graph, state, result, strict)
  23. if (er instanceof Error) return er
  24. }
  25. state[node] = PERMANENT_MARKER
  26. result.push(node)
  27. }
  28. function topologicalSort(graph, strict) {
  29. const result = []
  30. const state = {}
  31. const nodes = Object.keys(graph)
  32. const length = nodes.length
  33. for (let i = 0; i < length; ++i) {
  34. const er = walkGraph(nodes[i], graph, state, result, strict)
  35. if (er instanceof Error) return er
  36. }
  37. return result
  38. }
  39. module.exports = topologicalSort