[英]Tree-like data structure in JS that allows for fastest node lookup?
我將如何在JS中創建一個類似樹的數據結構,在那里,我可以訪問諸如父節點的引用,基於id的節點查找,訪問子節點的長度(數量),基於索引的查找等等?
這基本上就是我想象的API:
var rootNode = DataStructure.getRoot();
var child1 = rootNode.addNode('child1'); //added a node with id 'child1'
child1.addNode('innerChild1');
child1.addNode('innerChild2');
rootNode.getChildById('child1') //should be same node as var child1
rootNode.getAtIndex(0) //should be same node as var child1
child1.parent() //should be rootNode
child1.getAtIndex(0) // should be node with id 'innerChild1'
child1.getAtIndex(1) // should be node with id 'innerChild2'
child1.length() //should be 2
等等..
我理解它的一個廣泛的問題,但我想知道是否有人可以推薦一種方法來處理這個和/或任何可能已經這樣做的庫? 我應該動態創建XML並使用其本機方法嗎? 那會是最快的嗎?
您描述的數據結構可以很容易地實現如下:
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>
基於id的查找和基於索引的查找都采用常量(即O(1)
) 時間 。 希望有所幫助。
我在應用程序中有這樣的結構。 指定的API會使您難以創建所需的結構。 以下是我注意到的一些事情: DataStructure
是單例, addChild
不允許您添加addChild
節點的節點,索引是數字。 以下怎么樣?
成員:
方法:
成員:
方法:
方法:
這里沒有什么是不可改變的。 但是,您可以通過使用新的工廠方法並使上述方法中的更多內容始終強制樹的不變性。 這可能是也可能不是所希望的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.