type InputType = { id: string; parentId: string | null }; export type OutputType = T & { subtasks?: T[] }; export function taskListToTree( tasks: T[], addSubtasks = true ): OutputType[] { if (!addSubtasks) { return tasks; } const result: OutputType[] = []; const map = new Map(tasks.map((v) => [v.id, v])); for (const node of tasks) { const parent: OutputType | null = node.parentId ? (map.get(node.parentId) as OutputType) : null; if (parent) { if (!parent.subtasks) { parent.subtasks = [] as any; } parent.subtasks!.push(node as any); } else { result.push(node as any); } } return result; }