Turn any collection of objects into its own efficient tree or linked list using Symbol.
This library has been designed to provide an efficient backing data structure for DOM trees. You can also use this library as an efficient linked list. Any meta data is stored on your objects directly, which ensures any kind of insertion or deletion is performed in constant time. Because an ES6 Symbol is used, the meta data does not interfere with your object in any way.
Node.js 4+, io.js and modern browsers are supported.
Example
A linked list:
constSymbolTree=require('symbol-tree');consttree=newSymbolTree();leta={foo:'bar'};// or `new Whatever()`letb={foo:'baz'};letc={foo:'qux'};tree.insertBefore(b,a);// insert a before btree.insertAfter(b,c);// insert c after bconsole.log(tree.nextSibling(a) ===b);console.log(tree.nextSibling(b) ===c);console.log(tree.previousSibling(c) ===b);tree.remove(b);console.log(tree.nextSibling(a) ===c);
You can use this function to (optionally) initialize an object right after its creation, to take advantage of V8's fast properties. Also useful if you would like to freeze your object.
O(1)
Kind: instance method of SymbolTreeReturns: Object - object
Param
Type
object
Object
symbolTree.hasChildren(object) ⇒ Boolean
Returns true if the object has any children. Otherwise it returns false.
Find the preceding object (A) of the given object (B). An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order.
If set, root must be an inclusive ancestor of the return value (or else null is returned). This check assumes that root is also an inclusive ancestor of the given object
symbolTree.following(object, [options]) ⇒ Object
Find the following object (A) of the given object (B). An object A is following an object B if A and B are in the same tree and A comes after B in tree order.
O(n) (worst case) where n is the amount of objects in the entire tree
If set, root must be an inclusive ancestor of the return value (or else null is returned). This check assumes that root is also an inclusive ancestor of the given object
const SymbolTree = require('symbol-tree');
const tree = new SymbolTree();
let parent = {};
let a = {};
let b = {};
let c = {};
tree.prependChild(parent, a); // insert a as the first child
tree.appendChild(parent,c ); // insert c as the last child
tree.insertAfter(a, b); // insert b after a, it now has the same parent as a
console.log(tree.firstChild(parent) === a);
console.log(tree.nextSibling(tree.firstChild(parent)) === b);
console.log(tree.lastChild(parent) === c);
let grandparent = {};
tree.prependChild(grandparent, parent);
console.log(tree.firstChild(tree.firstChild(grandparent)) === a);