-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (74 loc) · 2.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
function groupedTopoSort(graph, groups) {
let cycles = [];
let cycleCache = [];
let visitedNodes = [];
function sortGroup(nodes, groupIndex) {
const group = {
contains: nodes,
visited: {},
sorted: [],
cycles: [],
};
function sortNodes(name, branch) {
if (group.visited[name]) {
return;
}
group.visited[name] = true;
graph[name].forEach(sortNodes);
group.sorted.push(name);
}
nodes.forEach(sortNodes);
function walkBranch(branchNodes, branch) {
branchNodes.forEach(node => {
const currentBranch = branch ? branch.slice() : [];
let cycle = currentBranch.includes(node);
currentBranch.push(node);
if (graph[node].length && !cycle) {
walkBranch(graph[node], currentBranch);
} else if (cycle) {
const cacheKey = branch.slice().sort().join();
if (!cycleCache.includes(cacheKey)) {
let cyclesIntoPreviousGroup = false;
for (let i = 0; i < branch.length; i++) {
if (visitedNodes.includes(branch[i])) {
cyclesIntoPreviousGroup = true;
break;
}
}
if (!cyclesIntoPreviousGroup) {
let cyclesBackIntoGroup = false;
for (let i = 1; i < branch.length; i++) {
if (group.contains.includes(branch[i])) {
cyclesBackIntoGroup = true;
break;
}
}
if (cyclesBackIntoGroup) {
group.cycles.push(currentBranch);
cycleCache.push(cacheKey);
}
}
}
}
});
}
walkBranch(nodes);
visitedNodes = visitedNodes.concat(group.contains);
return group;
}
const sortedGroups = groups.map(sortGroup);
const sorted = [];
sortedGroups.forEach((group, groupIndex) => {
cycles = cycles.concat(group.cycles);
sortedGroups.forEach(innerGroup => {
innerGroup.sorted.forEach(i => {
if (group.contains.includes(i) && !sorted.includes(i)) {
sorted.push(i);
}
});
});
});
return { sorted, cycles };
}
module.exports = groupedTopoSort;