-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
35 lines (26 loc) · 824 Bytes
/
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
'use strict'
const { countInDegrees, getRoots, getNonRoots } = require('./utils')
// :: { dependencyId: dependentId } -> [[taskId]]
const batchingToposort = dag => {
const indegrees = countInDegrees(dag)
const sorted = []
let roots = getRoots(indegrees)
while (roots.length) {
sorted.push(roots)
const newRoots = []
roots.forEach(root => {
dag[root].forEach(dependent => {
indegrees[dependent]--
if (indegrees[dependent] === 0) {
newRoots.push(dependent)
}
})
})
roots = newRoots
}
if (getNonRoots(indegrees).length) {
throw Error('Cycle(s) detected; toposort only works on acyclic graphs')
}
return sorted
}
module.exports = batchingToposort