Skip to content

Commit ce90b65

Browse files
committed
add topological sort utility
1 parent 69e97df commit ce90b65

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
export function topologicalSort<Key>(
2+
graph: Map<Key, Set<Key>>,
3+
options: { onCircularDependency: (path: Key[], start: Key) => void },
4+
): Key[] {
5+
let seen = new Set<Key>()
6+
let wip = new Set<Key>()
7+
8+
let sorted: Key[] = []
9+
10+
function visit(node: Key, path: Key[] = []) {
11+
if (!graph.has(node)) return
12+
if (seen.has(node)) return
13+
14+
// Circular dependency detected
15+
if (wip.has(node)) options.onCircularDependency?.(path, node)
16+
17+
wip.add(node)
18+
19+
for (let dependency of graph.get(node) ?? []) {
20+
path.push(node)
21+
visit(dependency, path)
22+
path.pop()
23+
}
24+
25+
seen.add(node)
26+
wip.delete(node)
27+
28+
sorted.push(node)
29+
}
30+
31+
for (let node of graph.keys()) {
32+
visit(node)
33+
}
34+
35+
return sorted
36+
}

0 commit comments

Comments
 (0)