SymbolTree.js
28.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
'use strict';
/**
* @module symbol-tree
* @author Joris van der Wel <joris@jorisvanderwel.com>
*/
const SymbolTreeNode = require('./SymbolTreeNode');
const TreePosition = require('./TreePosition');
const TreeIterator = require('./TreeIterator');
function returnTrue() {
return true;
}
function reverseArrayIndex(array, reverseIndex) {
return array[array.length - 1 - reverseIndex]; // no need to check `index >= 0`
}
class SymbolTree {
/**
* @constructor
* @alias module:symbol-tree
* @param {string} [description='SymbolTree data'] Description used for the Symbol
*/
constructor(description) {
this.symbol = Symbol(description || 'SymbolTree data');
}
/**
* 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)`
*
* @method
* @alias module:symbol-tree#initialize
* @param {Object} object
* @return {Object} object
*/
initialize(object) {
this._node(object);
return object;
}
_node(object) {
if (!object) {
return null;
}
const node = object[this.symbol];
if (node) {
return node;
}
return (object[this.symbol] = new SymbolTreeNode());
}
/**
* Returns `true` if the object has any children. Otherwise it returns `false`.
*
* * `O(1)`
*
* @method hasChildren
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Boolean}
*/
hasChildren(object) {
return this._node(object).hasChildren;
}
/**
* Returns the first child of the given object.
*
* * `O(1)`
*
* @method firstChild
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
firstChild(object) {
return this._node(object).firstChild;
}
/**
* Returns the last child of the given object.
*
* * `O(1)`
*
* @method lastChild
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
lastChild(object) {
return this._node(object).lastChild;
}
/**
* Returns the previous sibling of the given object.
*
* * `O(1)`
*
* @method previousSibling
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
previousSibling(object) {
return this._node(object).previousSibling;
}
/**
* Returns the next sibling of the given object.
*
* * `O(1)`
*
* @method nextSibling
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
nextSibling(object) {
return this._node(object).nextSibling;
}
/**
* Return the parent of the given object.
*
* * `O(1)`
*
* @method parent
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
parent(object) {
return this._node(object).parent;
}
/**
* Find the inclusive descendant that is last in tree order of the given object.
*
* * `O(n)` (worst case) where `n` is the depth of the subtree of `object`
*
* @method lastInclusiveDescendant
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object}
*/
lastInclusiveDescendant(object) {
let lastChild;
let current = object;
while ((lastChild = this._node(current).lastChild)) {
current = lastChild;
}
return current;
}
/**
* 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.
*
* * `O(n)` (worst case)
* * `O(1)` (amortized when walking the entire tree)
*
* @method preceding
* @memberOf module:symbol-tree#
* @param {Object} object
* @param {Object} [options]
* @param {Object} [options.root] 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`
* @return {?Object}
*/
preceding(object, options) {
const treeRoot = options && options.root;
if (object === treeRoot) {
return null;
}
const previousSibling = this._node(object).previousSibling;
if (previousSibling) {
return this.lastInclusiveDescendant(previousSibling);
}
// if there is no previous sibling return the parent (might be null)
return this._node(object).parent;
}
/**
* 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
* * `O(1)` (amortized when walking the entire tree)
*
* @method following
* @memberOf module:symbol-tree#
* @param {!Object} object
* @param {Object} [options]
* @param {Object} [options.root] 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`
* @param {Boolean} [options.skipChildren=false] If set, ignore the children of `object`
* @return {?Object}
*/
following(object, options) {
const treeRoot = options && options.root;
const skipChildren = options && options.skipChildren;
const firstChild = !skipChildren && this._node(object).firstChild;
if (firstChild) {
return firstChild;
}
let current = object;
do {
if (current === treeRoot) {
return null;
}
const nextSibling = this._node(current).nextSibling;
if (nextSibling) {
return nextSibling;
}
current = this._node(current).parent;
} while (current);
return null;
}
/**
* Append all children of the given object to an array.
*
* * `O(n)` where `n` is the amount of children of the given `parent`
*
* @method childrenToArray
* @memberOf module:symbol-tree#
* @param {Object} parent
* @param {Object} [options]
* @param {Object[]} [options.array=[]]
* @param {Function} [options.filter] Function to test each object before it is added to the array.
* Invoked with arguments (object). Should return `true` if an object
* is to be included.
* @param {*} [options.thisArg] Value to use as `this` when executing `filter`.
* @return {Object[]}
*/
childrenToArray(parent, options) {
const array = (options && options.array) || [];
const filter = (options && options.filter) || returnTrue;
const thisArg = (options && options.thisArg) || undefined;
const parentNode = this._node(parent);
let object = parentNode.firstChild;
let index = 0;
while (object) {
const node = this._node(object);
node.setCachedIndex(parentNode, index);
if (filter.call(thisArg, object)) {
array.push(object);
}
object = node.nextSibling;
++index;
}
return array;
}
/**
* Append all inclusive ancestors of the given object to an array.
*
* * `O(n)` where `n` is the amount of ancestors of the given `object`
*
* @method ancestorsToArray
* @memberOf module:symbol-tree#
* @param {Object} object
* @param {Object} [options]
* @param {Object[]} [options.array=[]]
* @param {Function} [options.filter] Function to test each object before it is added to the array.
* Invoked with arguments (object). Should return `true` if an object
* is to be included.
* @param {*} [options.thisArg] Value to use as `this` when executing `filter`.
* @return {Object[]}
*/
ancestorsToArray(object, options) {
const array = (options && options.array) || [];
const filter = (options && options.filter) || returnTrue;
const thisArg = (options && options.thisArg) || undefined;
let ancestor = object;
while (ancestor) {
if (filter.call(thisArg, ancestor)) {
array.push(ancestor);
}
ancestor = this._node(ancestor).parent;
}
return array;
}
/**
* Append all descendants of the given object to an array (in tree order).
*
* * `O(n)` where `n` is the amount of objects in the sub-tree of the given `object`
*
* @method treeToArray
* @memberOf module:symbol-tree#
* @param {Object} root
* @param {Object} [options]
* @param {Object[]} [options.array=[]]
* @param {Function} [options.filter] Function to test each object before it is added to the array.
* Invoked with arguments (object). Should return `true` if an object
* is to be included.
* @param {*} [options.thisArg] Value to use as `this` when executing `filter`.
* @return {Object[]}
*/
treeToArray(root, options) {
const array = (options && options.array) || [];
const filter = (options && options.filter) || returnTrue;
const thisArg = (options && options.thisArg) || undefined;
let object = root;
while (object) {
if (filter.call(thisArg, object)) {
array.push(object);
}
object = this.following(object, {root: root});
}
return array;
}
/**
* Iterate over all children of the given object
*
* * `O(1)` for a single iteration
*
* @method childrenIterator
* @memberOf module:symbol-tree#
* @param {Object} parent
* @param {Object} [options]
* @param {Boolean} [options.reverse=false]
* @return {Object} An iterable iterator (ES6)
*/
childrenIterator(parent, options) {
const reverse = options && options.reverse;
const parentNode = this._node(parent);
return new TreeIterator(
this,
parent,
reverse ? parentNode.lastChild : parentNode.firstChild,
reverse ? TreeIterator.PREV : TreeIterator.NEXT
);
}
/**
* Iterate over all the previous siblings of the given object. (in reverse tree order)
*
* * `O(1)` for a single iteration
*
* @method previousSiblingsIterator
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object} An iterable iterator (ES6)
*/
previousSiblingsIterator(object) {
return new TreeIterator(
this,
object,
this._node(object).previousSibling,
TreeIterator.PREV
);
}
/**
* Iterate over all the next siblings of the given object. (in tree order)
*
* * `O(1)` for a single iteration
*
* @method nextSiblingsIterator
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object} An iterable iterator (ES6)
*/
nextSiblingsIterator(object) {
return new TreeIterator(
this,
object,
this._node(object).nextSibling,
TreeIterator.NEXT
);
}
/**
* Iterate over all inclusive ancestors of the given object
*
* * `O(1)` for a single iteration
*
* @method ancestorsIterator
* @memberOf module:symbol-tree#
* @param {Object} object
* @return {Object} An iterable iterator (ES6)
*/
ancestorsIterator(object) {
return new TreeIterator(
this,
object,
object,
TreeIterator.PARENT
);
}
/**
* Iterate over all descendants of the given object (in tree order).
*
* Where `n` is the amount of objects in the sub-tree of the given `root`:
*
* * `O(n)` (worst case for a single iteration)
* * `O(n)` (amortized, when completing the iterator)
*
* @method treeIterator
* @memberOf module:symbol-tree#
* @param {Object} root
* @param {Object} options
* @param {Boolean} [options.reverse=false]
* @return {Object} An iterable iterator (ES6)
*/
treeIterator(root, options) {
const reverse = options && options.reverse;
return new TreeIterator(
this,
root,
reverse ? this.lastInclusiveDescendant(root) : root,
reverse ? TreeIterator.PRECEDING : TreeIterator.FOLLOWING
);
}
/**
* Find the index of the given object (the number of preceding siblings).
*
* * `O(n)` where `n` is the amount of preceding siblings
* * `O(1)` (amortized, if the tree is not modified)
*
* @method index
* @memberOf module:symbol-tree#
* @param {Object} child
* @return {Number} The number of preceding siblings, or -1 if the object has no parent
*/
index(child) {
const childNode = this._node(child);
const parentNode = this._node(childNode.parent);
if (!parentNode) {
// In principal, you could also find out the number of preceding siblings
// for objects that do not have a parent. This method limits itself only to
// objects that have a parent because that lets us optimize more.
return -1;
}
let currentIndex = childNode.getCachedIndex(parentNode);
if (currentIndex >= 0) {
return currentIndex;
}
currentIndex = 0;
let object = parentNode.firstChild;
if (parentNode.childIndexCachedUpTo) {
const cachedUpToNode = this._node(parentNode.childIndexCachedUpTo);
object = cachedUpToNode.nextSibling;
currentIndex = cachedUpToNode.getCachedIndex(parentNode) + 1;
}
while (object) {
const node = this._node(object);
node.setCachedIndex(parentNode, currentIndex);
if (object === child) {
break;
}
++currentIndex;
object = node.nextSibling;
}
parentNode.childIndexCachedUpTo = child;
return currentIndex;
}
/**
* Calculate the number of children.
*
* * `O(n)` where `n` is the amount of children
* * `O(1)` (amortized, if the tree is not modified)
*
* @method childrenCount
* @memberOf module:symbol-tree#
* @param {Object} parent
* @return {Number}
*/
childrenCount(parent) {
const parentNode = this._node(parent);
if (!parentNode.lastChild) {
return 0;
}
return this.index(parentNode.lastChild) + 1;
}
/**
* Compare the position of an object relative to another object. A bit set is returned:
*
* <ul>
* <li>DISCONNECTED : 1</li>
* <li>PRECEDING : 2</li>
* <li>FOLLOWING : 4</li>
* <li>CONTAINS : 8</li>
* <li>CONTAINED_BY : 16</li>
* </ul>
*
* The semantics are the same as compareDocumentPosition in DOM, with the exception that
* DISCONNECTED never occurs with any other bit.
*
* where `n` and `m` are the amount of ancestors of `left` and `right`;
* where `o` is the amount of children of the lowest common ancestor of `left` and `right`:
*
* * `O(n + m + o)` (worst case)
* * `O(n + m)` (amortized, if the tree is not modified)
*
* @method compareTreePosition
* @memberOf module:symbol-tree#
* @param {Object} left
* @param {Object} right
* @return {Number}
*/
compareTreePosition(left, right) {
// In DOM terms:
// left = reference / context object
// right = other
if (left === right) {
return 0;
}
/* jshint -W016 */
const leftAncestors = []; { // inclusive
let leftAncestor = left;
while (leftAncestor) {
if (leftAncestor === right) {
return TreePosition.CONTAINS | TreePosition.PRECEDING;
// other is ancestor of reference
}
leftAncestors.push(leftAncestor);
leftAncestor = this.parent(leftAncestor);
}
}
const rightAncestors = []; {
let rightAncestor = right;
while (rightAncestor) {
if (rightAncestor === left) {
return TreePosition.CONTAINED_BY | TreePosition.FOLLOWING;
}
rightAncestors.push(rightAncestor);
rightAncestor = this.parent(rightAncestor);
}
}
const root = reverseArrayIndex(leftAncestors, 0);
if (!root || root !== reverseArrayIndex(rightAncestors, 0)) {
// note: unlike DOM, preceding / following is not set here
return TreePosition.DISCONNECTED;
}
// find the lowest common ancestor
let commonAncestorIndex = 0;
const ancestorsMinLength = Math.min(leftAncestors.length, rightAncestors.length);
for (let i = 0; i < ancestorsMinLength; ++i) {
const leftAncestor = reverseArrayIndex(leftAncestors, i);
const rightAncestor = reverseArrayIndex(rightAncestors, i);
if (leftAncestor !== rightAncestor) {
break;
}
commonAncestorIndex = i;
}
// indexes within the common ancestor
const leftIndex = this.index(reverseArrayIndex(leftAncestors, commonAncestorIndex + 1));
const rightIndex = this.index(reverseArrayIndex(rightAncestors, commonAncestorIndex + 1));
return rightIndex < leftIndex
? TreePosition.PRECEDING
: TreePosition.FOLLOWING;
}
/**
* Remove the object from this tree.
* Has no effect if already removed.
*
* * `O(1)`
*
* @method remove
* @memberOf module:symbol-tree#
* @param {Object} removeObject
* @return {Object} removeObject
*/
remove(removeObject) {
const removeNode = this._node(removeObject);
const parentNode = this._node(removeNode.parent);
const prevNode = this._node(removeNode.previousSibling);
const nextNode = this._node(removeNode.nextSibling);
if (parentNode) {
if (parentNode.firstChild === removeObject) {
parentNode.firstChild = removeNode.nextSibling;
}
if (parentNode.lastChild === removeObject) {
parentNode.lastChild = removeNode.previousSibling;
}
}
if (prevNode) {
prevNode.nextSibling = removeNode.nextSibling;
}
if (nextNode) {
nextNode.previousSibling = removeNode.previousSibling;
}
removeNode.parent = null;
removeNode.previousSibling = null;
removeNode.nextSibling = null;
if (parentNode) {
parentNode.childrenChanged();
}
return removeObject;
}
/**
* Insert the given object before the reference object.
* `newObject` is now the previous sibling of `referenceObject`.
*
* * `O(1)`
*
* @method insertBefore
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
insertBefore(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const prevNode = this._node(referenceNode.previousSibling);
const newNode = this._node(newObject);
const parentNode = this._node(referenceNode.parent);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
newNode.parent = referenceNode.parent;
newNode.previousSibling = referenceNode.previousSibling;
newNode.nextSibling = referenceObject;
referenceNode.previousSibling = newObject;
if (prevNode) {
prevNode.nextSibling = newObject;
}
if (parentNode && parentNode.firstChild === referenceObject) {
parentNode.firstChild = newObject;
}
if (parentNode) {
parentNode.childrenChanged();
}
return newObject;
}
/**
* Insert the given object after the reference object.
* `newObject` is now the next sibling of `referenceObject`.
*
* * `O(1)`
*
* @method insertAfter
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
insertAfter(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const nextNode = this._node(referenceNode.nextSibling);
const newNode = this._node(newObject);
const parentNode = this._node(referenceNode.parent);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
newNode.parent = referenceNode.parent;
newNode.previousSibling = referenceObject;
newNode.nextSibling = referenceNode.nextSibling;
referenceNode.nextSibling = newObject;
if (nextNode) {
nextNode.previousSibling = newObject;
}
if (parentNode && parentNode.lastChild === referenceObject) {
parentNode.lastChild = newObject;
}
if (parentNode) {
parentNode.childrenChanged();
}
return newObject;
}
/**
* Insert the given object as the first child of the given reference object.
* `newObject` is now the first child of `referenceObject`.
*
* * `O(1)`
*
* @method prependChild
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
prependChild(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const newNode = this._node(newObject);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
if (referenceNode.hasChildren) {
this.insertBefore(referenceNode.firstChild, newObject);
}
else {
newNode.parent = referenceObject;
referenceNode.firstChild = newObject;
referenceNode.lastChild = newObject;
referenceNode.childrenChanged();
}
return newObject;
}
/**
* Insert the given object as the last child of the given reference object.
* `newObject` is now the last child of `referenceObject`.
*
* * `O(1)`
*
* @method appendChild
* @memberOf module:symbol-tree#
* @param {Object} referenceObject
* @param {Object} newObject
* @throws {Error} If the newObject is already present in this SymbolTree
* @return {Object} newObject
*/
appendChild(referenceObject, newObject) {
const referenceNode = this._node(referenceObject);
const newNode = this._node(newObject);
if (newNode.isAttached) {
throw Error('Given object is already present in this SymbolTree, remove it first');
}
if (referenceNode.hasChildren) {
this.insertAfter(referenceNode.lastChild, newObject);
}
else {
newNode.parent = referenceObject;
referenceNode.firstChild = newObject;
referenceNode.lastChild = newObject;
referenceNode.childrenChanged();
}
return newObject;
}
}
module.exports = SymbolTree;
SymbolTree.TreePosition = TreePosition;