-
Notifications
You must be signed in to change notification settings - Fork 0
/
getTopologicalOrder.js
63 lines (54 loc) · 1.42 KB
/
getTopologicalOrder.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
/**
* Given a `Variable` returns traversal order that visits all
* parents before children.
*
* Implementation is not recursive and can be used on large graphs.
*/
export function getTopologicalOrder(start) {
recalculateParentsCount(start);
let traversalOrder = [];
let visited = new Set();
let queue = [start];
while (queue.length > 0) {
let node = queue.shift();
if (visited.has(node)) continue;
if (node.parentCount !== 0) {
throw new Error('Should have no parents at this point');
}
traversalOrder.push(node);
visited.add(node);
node.children.forEach(visitAndEnqueueOrphans);
}
return traversalOrder;
function visitAndEnqueueOrphans(child) {
child.parentCount -= 1
if (child.parentCount === 0) {
queue.push(child);
}
}
}
export function recalculateParentsCount(from) {
setParentCountToZero(from)
let queue = [from];
let visited = new Set();
while (queue.length > 0) {
let node = queue.pop();
if (visited.has(node)) continue;
visited.add(node);
node.children.forEach(child => {
child.parentCount += 1;
queue.push(child);
});
}
}
function setParentCountToZero(from) {
let queue = [from];
let visited = new Set();
while (queue.length > 0) {
let node = queue.pop();
if (visited.has(node)) continue;
visited.add(node);
node.parentCount = 0;
node.children.forEach(child => queue.push(child));
}
}