-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgraphUtils.ts
55 lines (44 loc) · 1.11 KB
/
graphUtils.ts
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
// Copyright 2020 Cognite AS
import { Queue } from './queue';
export interface Node<T> {
parentNode?: Node<T>;
data: T;
}
/** @hidden */
export function topologicalSort<T>(nodes: Node<T>[]): Node<T>[] {
const queue = new Queue<Node<T>>();
const sortedList: Node<T>[] = [];
const childrenMap = getChildrenMap(nodes);
// insert root nodes
for (const node of nodes) {
if (!node.parentNode) {
queue.add(node);
}
}
while (queue.size() !== 0) {
const node = queue.last();
queue.remove();
sortedList.push(node);
const children = childrenMap.get(node);
if (children) {
children.forEach(queue.add);
}
}
if (sortedList.length !== nodes.length) {
throw Error('Impossible to topological sort nodes');
}
return sortedList;
}
function getChildrenMap<T>(nodes: Node<T>[]): Map<Node<T>, Node<T>[]> {
const childrenMap = new Map();
for (const node of nodes) {
childrenMap.set(node, []);
}
for (const node of nodes) {
const { parentNode } = node;
if (parentNode) {
childrenMap.get(parentNode).push(node);
}
}
return childrenMap;
}