You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.2 KiB

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