topologicalSort.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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) {
  14. return;
  15. }
  16. if (state[node] === TEMPORARY_MARKER) {
  17. if (strict) {
  18. return createError(node, graph);
  19. }
  20. return;
  21. }
  22. state[node] = TEMPORARY_MARKER;
  23. const children = graph[node];
  24. const length = children.length;
  25. for (let i = 0; i < length; ++i) {
  26. const error = walkGraph(children[i], graph, state, result, strict);
  27. if (error instanceof Error) {
  28. return error;
  29. }
  30. }
  31. state[node] = PERMANENT_MARKER;
  32. result.push(node);
  33. }
  34. function topologicalSort(graph, strict) {
  35. const result = [];
  36. const state = {};
  37. const nodes = Object.keys(graph);
  38. const length = nodes.length;
  39. for (let i = 0; i < length; ++i) {
  40. const er = walkGraph(nodes[i], graph, state, result, strict);
  41. if (er instanceof Error) {
  42. return er;
  43. }
  44. }
  45. return result;
  46. }
  47. module.exports = topologicalSort;