-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequence.ts
63 lines (51 loc) · 1.29 KB
/
sequence.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
56
57
58
59
60
61
62
63
import { YError } from 'yerror';
export type Node = {
__name: string;
__childNodes?: Node[];
};
const MAX_ITERATIONS = 99;
export function buildInitializationSequence<T extends Node>(
rootNode: T,
): string[][] {
const batches: string[][] = [];
let i = 0;
while (i < MAX_ITERATIONS) {
const batch = recursivelyGetNextSequenceBatch(rootNode, batches);
if (0 === batch.length) {
break;
}
batches.push(batch);
i++;
}
if (i === MAX_ITERATIONS) {
throw new YError('E_PROBABLE_CIRCULAR_DEPENDENCY');
}
return batches;
}
function recursivelyGetNextSequenceBatch(
node: Node,
batches: string[][],
batch: string[] = [],
): string[] {
const nodeIsALeaf = !(node.__childNodes && node.__childNodes.length);
if (nodeIsInBatches(batches, node)) {
return batch;
}
if (
nodeIsALeaf ||
(node.__childNodes as Node[]).every((childNode: Node) =>
nodeIsInBatches(batches, childNode),
)
) {
return batch.concat(node.__name);
}
return (node.__childNodes as Node[]).reduce(
(batch, childNode) => [
...new Set(recursivelyGetNextSequenceBatch(childNode, batches, batch)),
],
batch,
);
}
function nodeIsInBatches(batches: string[][], node: Node): boolean {
return batches.some((batch) => batch.includes(node.__name));
}