import { List, Record } from "immutable";
const TaskRecord = Record({ id: -1, name: "", parent: undefined });
const TaskNodeRecord = Record({ id: -1, name: "", parent: undefined, children: List<Task>() });
const ID = "id";
const NAME = "name";
const PARENT = "parent";
const CHILDREN = "children";
class Task extends TaskRecord {
constructor(id: number, name: string, parent = undefined) {
super({ id, name, parent });
}
public id(): number {
return this.get(ID);
}
public name(): string {
return this.get(NAME);
}
public parent(): number {
return this.get(PARENT);
}
public toNode(children: List<TaskNode>): TaskNode {
return new TaskNode(this.id(), this.name(), this.parent(), children);
}
}
class TaskNode extends TaskNodeRecord {
constructor(id: number, name: string, parent = undefined, children = List<TaskNode>()) {
super({ id, name, parent, children });
}
public id(): number {
return this.get(ID);
}
public name(): string {
return this.get(NAME);
}
public parent(): number {
return this.get(PARENT);
}
public children(): List<Task> {
return this.get(CHILDREN);
}
}
const tasks: List<Task> = List<Task>([
new Task(1, "Root"),
new Task(2, "A-1", 1),
new Task(3, "A-1-1", 2),
new Task(4, "B-1", 1)
]);
const roots = tasks.filter((task) =>
task.parent() === undefined
).toList();
const createTree = (nodes: List<Task>, origList: List<Task>) =>
nodes.map((node) => {
const children = origList.filter((task) => task.parent() === node.id());
const childrenNode = createTree(children.toList(), origList);
return node.toNode(childrenNode);
});
console.log(createTree(roots, tasks));