-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraversal.ts
101 lines (93 loc) · 2.44 KB
/
traversal.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { Unit } from '../model';
import { Visitor } from './visitor';
import { TraversalContext } from './traversal.type';
function updatedContext<T extends TraversalContext>(
parentContext: T,
index: number,
totalChildren: number
): T {
return {
...parentContext,
level: parentContext.level + 1,
last: index === totalChildren - 1,
};
}
export function visitAllUnits<T extends TraversalContext>(
unit: Unit,
visitor: Visitor<T>,
context: T = { level: 0, last: false } as T
): void {
if (unit.type === 'department') {
visitor?.visitDepartment?.(unit, context);
unit.children.forEach((child, index) => {
visitAllUnits(
child,
visitor,
updatedContext(context, index, unit.children.length)
);
});
} else if (unit.type === 'employee') {
visitor?.visitEmployee?.(unit, context);
unit.tasks.forEach((task, index) => {
visitor?.visitTask?.(
task,
updatedContext(context, index, unit.tasks.length)
);
});
}
}
export function visitAllDepartments<T extends TraversalContext>(
unit: Unit,
visitor: Visitor<T>,
context: T = { level: 0, last: false } as T
): void {
if (unit.type === 'department') {
visitor?.visitDepartment?.(unit, context);
unit.children.forEach((child, index) => {
visitAllDepartments(
child,
visitor,
updatedContext(context, index, unit.children.length)
);
});
}
}
export function visitAllEmployees<T extends TraversalContext>(
unit: Unit,
visitor: Visitor<T>,
context: T = { level: 0, last: false } as T
): void {
if (unit.type === 'department') {
unit.children.forEach((child, index) => {
visitAllEmployees(
child,
visitor,
updatedContext(context, index, unit.children.length)
);
});
} else if (unit.type === 'employee') {
visitor?.visitEmployee?.(unit, context);
}
}
export function visitAllTasks<T extends TraversalContext>(
unit: Unit,
visitor: Visitor<T>,
context: T = { level: 0, last: false } as T
): void {
if (unit.type === 'department') {
unit.children.forEach((child, index) => {
visitAllTasks(
child,
visitor,
updatedContext(context, index, unit.children.length)
);
});
} else if (unit.type === 'employee') {
unit.tasks.forEach((task, index) => {
visitor?.visitTask?.(
task,
updatedContext(context, index, unit.tasks.length)
);
});
}
}