Tree-like data structure in JS that allows for fastest node lookup? Tree-like data structure in JS that allows for fastest node lookup? json json

Tree-like data structure in JS that allows for fastest node lookup?


The data structure you described can be easily implemented as follows:

var Tree = defclass({    constructor: function (parent) {        this.parent   = parent || null; // null for root node        this.children = {};             // for id based lookup        this.ids      = [];             // for index based lookup        this.length   = 0;              // for ease of access    },    addNode: function (id) {        var children = this.children;        if (children.hasOwnProperty(id)) throw new Error(id + " exists");        return children[this.ids[this.length++] = id] = new Tree(this);    },    getChildById: function (id) {        var children = this.children;        if (children.hasOwnProperty(id)) return children[id];        throw new Error(id + " does not exist");    },    getAtIndex: function (index) {        return this.getChildById(this.ids[index]);    }});function defclass(prototype) {    var constructor = prototype.constructor;    constructor.prototype = prototype;    return constructor;}
<script>    setTimeout(function () {        var rootNode    = new Tree;        var child1      = rootNode.addNode("child1");        var innerChild1 = child1.addNode("innerChild1");        var innerChild2 = child1.addNode("innerChild2");        console.assert(rootNode.getChildById("child1") === child1);        console.assert(rootNode.getAtIndex(0)          === child1);        console.assert(child1.parent                   === rootNode);        console.assert(child1.getAtIndex(0)            === innerChild1);        console.assert(child1.getAtIndex(1)            === innerChild2);        console.assert(child1.length                   === 2);        alert("success");    }, 0);</script>