-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathrelationships.ts
More file actions
38 lines (32 loc) · 1020 Bytes
/
relationships.ts
File metadata and controls
38 lines (32 loc) · 1020 Bytes
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
import type { TaskId } from "@/api/domain/task";
import type { Task } from "@/data/task";
export type TaskTree = Task & { children: TaskTree[] };
// Builds a task tree, preserving the sorting order.
export function buildTaskTree(tasks: Task[]): TaskTree[] {
const mapping = new Map<TaskId, TaskTree>();
const roots: TaskId[] = [];
for (const task of tasks) {
mapping.set(task.id, { ...task, children: [] });
}
for (const task of tasks) {
if (task.parentId === undefined || !mapping.has(task.parentId)) {
roots.push(task.id);
continue;
}
const parent = mapping.get(task.parentId);
if (parent !== undefined) {
const child = mapping.get(task.id);
if (child === undefined) {
throw new Error("Expected to find task in map");
}
parent.children.push(child);
}
}
return roots.map((id) => {
const tree = mapping.get(id);
if (tree === undefined) {
throw new Error("Expected to find task in map");
}
return tree;
});
}