JSFiddle - React, Tailwind, and code Playground

by lchau

HTML

A B C A -> B A -> C A B C A C A | => | => / \ B B C

JavaScript

function shuffle(array) {
    var counter = array.length - 1;
    var tmp;
    var index;
    for (; counter > 0; counter--) {
        index = Math.floor(Math.random() * counter);
        tmp = array[counter];
        array[counter] = array[index];
        array[index] = tmp;
    }
}

function Node(id, parentId, type) {
    return {
        "id": id,
            "parentId": parentId,
            "children": []
    };
}

function findParents(list) {
    var parents = [];
    list.forEach(function (element, index, array) {
        if (element.parentId === null) {
            parents.push(element);
        }
    });
    return parents;
}

function generateMap(list) {
    var result = {};
    if (list) {
        list.forEach(function (o, index, array) {
            // result[o.parentId] = o; // creates { "A": o }, where o is the node
            result[o.id] = o;
        });
    }
    return result;
}

var list = [
new Node("A", null, "Property"),
new Node("B", "A", "Asset"),
new Node("C", "A", "Building"),
new Node("D", "C", "Floor"),
new Node("E", "D", "Room"),
new Node("F", "D", "Asset"),
new Node("G", "E", "Asset"),
new Node("H", "C", "Asset"),
new Node("A1", null, "Property"),
new Node("B1", "A1", "Asset"),
new Node("C1", "A1", "Building"),
new Node("D1", "C1", "Floor"),
new Node("E1", "D1", "Room"),
new Node("F1", "D1", "Asset"),
new Node("G1", "E1", "Asset"),
new Node("H1", "C1", "Asset")];
shuffle(list);

var list1 = [("A", "B"), ("A", "C")];

var map = generateMap(list);
var tree = {};

// For each node to process
for (var i = 0; i < list.length; i++) {
    // Get the parent of that node
    var parentId = list[i].parentId;
    // (This is the id of the node)
    var id = list[i].id;
    // If there's no parent
    if (parentId == null) {
        // ...
        tree[parentId] = list[i];
    } else {
        // Otherwise, there is a parent
        // Look up the parent in the map and then make 
        // this node one of its children
       ...