ababup1192
12/13/2016 - 2:54 AM

tree.ts

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));
import { List, Map } from "immutable";

const tasks: List<Map<string, any>> = List<Map<string, any>>([
    Map({ id: 1, name: "Root" }),
    Map({ id: 2, name: "A-1", parent: 1 }),
    Map({ id: 3, name: "A-1-1", parent: 2 }),
    Map({ id: 4, name: "B-1", parent: 1 })
]);

const roots = tasks.filter((task) =>
    task.get("parent") === undefined
).toList();

const createTree = (nodes: List<Map<string, any>>) =>
    nodes.map((node) => {
        const children = tasks.filter((task) => task.get("parent") === node.get("id"));
        const childrenNode = createTree(children.toList());
        return node.set("children", childrenNode);
    });

console.log(createTree(roots));