-
Notifications
You must be signed in to change notification settings - Fork 184
/
sorted-set.js
780 lines (708 loc) · 22 KB
/
sorted-set.js
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
"use strict";
module.exports = SortedSet;
var Shim = require("./shim");
var GenericCollection = require("./generic-collection");
var GenericSet = require("./generic-set");
var PropertyChanges = require("./listen/property-changes");
var RangeChanges = require("./listen/range-changes");
var TreeLog = require("./tree-log");
function SortedSet(values, equals, compare, getDefault) {
if (!(this instanceof SortedSet)) {
return new SortedSet(values, equals, compare, getDefault);
}
this.contentEquals = equals || Object.equals;
this.contentCompare = compare || Object.compare;
this.getDefault = getDefault || Function.noop;
this.root = null;
this.length = 0;
this.addEach(values);
}
// hack so require("sorted-set").SortedSet will work in MontageJS
SortedSet.SortedSet = SortedSet;
Object.addEach(SortedSet.prototype, GenericCollection.prototype);
Object.addEach(SortedSet.prototype, GenericSet.prototype);
Object.addEach(SortedSet.prototype, PropertyChanges.prototype);
Object.addEach(SortedSet.prototype, RangeChanges.prototype);
Object.defineProperty(SortedSet.prototype,"size",GenericCollection._sizePropertyDescriptor);
SortedSet.from = GenericCollection.from;
SortedSet.prototype.isSorted = true;
SortedSet.prototype.constructClone = function (values) {
return new this.constructor(
values,
this.contentEquals,
this.contentCompare,
this.getDefault
);
};
SortedSet.prototype.has = function (value, equals) {
if (equals) {
throw new Error("SortedSet#has does not support second argument: equals");
}
if (this.root) {
this.splay(value);
return this.contentEquals(value, this.root.value);
} else {
return false;
}
};
SortedSet.prototype.get = function (value, equals) {
if (equals) {
throw new Error("SortedSet#get does not support second argument: equals");
}
if (this.root) {
this.splay(value);
if (this.contentEquals(value, this.root.value)) {
return this.root.value;
}
}
return this.getDefault(value);
};
SortedSet.prototype.add = function (value) {
var node = new this.Node(value);
if (this.root) {
this.splay(value);
if (!this.contentEquals(value, this.root.value)) {
var comparison = this.contentCompare(value, this.root.value);
if (comparison === 0) {
throw new Error("SortedSet cannot contain incomparable but inequal values: " + value + " and " + this.root.value);
}
if (this.dispatchesRangeChanges) {
this.dispatchBeforeRangeChange([value], [], this.root.index);
}
if (comparison < 0) {
// rotate right
// R N
// / \ -> / \
// l r l R
// : : : \
// r
// :
node.right = this.root;
node.left = this.root.left;
this.root.left = null;
this.root.touch();
} else {
// rotate left
// R N
// / \ -> / \
// l r R r
// : : / :
// l
// :
node.left = this.root;
node.right = this.root.right;
this.root.right = null;
this.root.touch();
}
node.touch();
this.root = node;
this.length++;
if (this.dispatchesRangeChanges) {
this.dispatchRangeChange([value], [], this.root.index);
}
return true;
}
} else {
if (this.dispatchesRangeChanges) {
this.dispatchBeforeRangeChange([value], [], 0);
}
this.root = node;
this.length++;
if (this.dispatchesRangeChanges) {
this.dispatchRangeChange([value], [], 0);
}
return true;
}
return false;
};
SortedSet.prototype['delete'] = function (value, equals) {
if (equals) {
throw new Error("SortedSet#delete does not support second argument: equals");
}
if (this.root) {
this.splay(value);
if (this.contentEquals(value, this.root.value)) {
var index = this.root.index;
if (this.dispatchesRangeChanges) {
this.dispatchBeforeRangeChange([], [value], index);
}
if (!this.root.left) {
this.root = this.root.right;
} else {
// remove the right side of the tree,
var right = this.root.right;
this.root = this.root.left;
// the tree now only contains the left side of the tree, so all
// values are less than the value deleted.
// splay so that the root has an empty right child
this.splay(value);
// put the right side of the tree back
this.root.right = right;
}
this.length--;
if (this.root) {
this.root.touch();
}
if (this.dispatchesRangeChanges) {
this.dispatchRangeChange([], [value], index);
}
return true;
}
}
return false;
};
SortedSet.prototype.indexOf = function (value, index) {
if (index) {
throw new Error("SortedSet#indexOf does not support second argument: startIndex");
}
if (this.root) {
this.splay(value);
if (this.contentEquals(value, this.root.value)) {
return this.root.index;
}
}
return -1;
};
SortedSet.prototype.find = function (value, equals, index) {
if (equals) {
throw new Error("SortedSet#find does not support second argument: equals");
}
if (index) {
// TODO contemplate using splayIndex to isolate a subtree in
// which to search.
throw new Error("SortedSet#find does not support third argument: index");
}
if (this.root) {
this.splay(value);
if (this.contentEquals(value, this.root.value)) {
return this.root;
}
}
};
SortedSet.prototype.findGreatest = function (at) {
if (this.root) {
at = at || this.root;
while (at.right) {
at = at.right;
}
return at;
}
};
SortedSet.prototype.findLeast = function (at) {
if (this.root) {
at = at || this.root;
while (at.left) {
at = at.left;
}
return at;
}
};
SortedSet.prototype.findGreatestLessThanOrEqual = function (value) {
if (this.root) {
this.splay(value);
if (this.contentCompare(this.root.value, value) > 0) {
return this.root.getPrevious();
} else {
return this.root;
}
}
};
SortedSet.prototype.findGreatestLessThan = function (value) {
if (this.root) {
this.splay(value);
if (this.contentCompare(this.root.value, value) >= 0) {
return this.root.getPrevious();
} else {
return this.root;
}
}
};
SortedSet.prototype.findLeastGreaterThanOrEqual = function (value) {
if (this.root) {
this.splay(value);
if (this.contentCompare(this.root.value, value) >= 0) {
return this.root;
} else {
return this.root.getNext();
}
}
};
SortedSet.prototype.findLeastGreaterThan = function (value) {
if (this.root) {
this.splay(value);
if (this.contentCompare(this.root.value, value) <= 0) {
return this.root.getNext();
} else {
return this.root;
}
}
};
SortedSet.prototype.pop = function () {
if (this.root) {
var found = this.findGreatest();
this["delete"](found.value);
return found.value;
}
};
SortedSet.prototype.shift = function () {
if (this.root) {
var found = this.findLeast();
this["delete"](found.value);
return found.value;
}
};
SortedSet.prototype.push = function () {
this.addEach(arguments);
};
SortedSet.prototype.unshift = function () {
this.addEach(arguments);
};
SortedSet.prototype.slice = function (start, end) {
var temp;
start = start || 0;
end = end || this.length;
if (start < 0) {
start += this.length;
}
if (end < 0) {
end += this.length;
}
var sliced = [];
if (this.root) {
this.splayIndex(start);
while (this.root.index < end) {
sliced.push(this.root.value);
if (!this.root.right) {
break;
}
this.splay(this.root.getNext().value);
}
}
return sliced;
};
SortedSet.prototype.splice = function (at, length /*...plus*/) {
return this.swap(at, length, Array.prototype.slice.call(arguments, 2));
};
SortedSet.prototype.swap = function (start, length, plus) {
if (start === undefined && length === undefined) {
return [];
}
start = start || 0;
if (start < 0) {
start += this.length;
}
if (length === undefined) {
length = Infinity;
}
var swapped = [];
if (this.root) {
// start
this.splayIndex(start);
// minus length
for (var i = 0; i < length; i++) {
swapped.push(this.root.value);
var next = this.root.getNext();
this["delete"](this.root.value);
if (!next) {
break;
}
this.splay(next.value);
}
}
// plus
this.addEach(plus);
return swapped;
};
// This is the simplified top-down splaying algorithm from: "Self-adjusting
// Binary Search Trees" by Sleator and Tarjan. Guarantees that root.value
// equals value if value exists. If value does not exist, then root will be
// the node whose value either immediately preceeds or immediately follows value.
// - as described in https://github.com/hij1nx/forest
SortedSet.prototype.splay = function (value) {
var stub, left, right, temp, root, history;
if (!this.root) {
return;
}
// Create a stub node. The use of the stub node is a bit
// counter-intuitive: The right child of the stub node will hold the L tree
// of the algorithm. The left child of the stub node will hold the R tree
// of the algorithm. Using a stub node, left and right will always be
// nodes and we avoid special cases.
// - http://code.google.com/p/v8/source/browse/branches/bleeding_edge/src/splay-tree-inl.h
stub = left = right = new this.Node();
// The history is an upside down tree used to propagate new tree sizes back
// up the left and right arms of a traversal. The right children of the
// transitive left side of the tree will be former roots while linking
// left. The left children of the transitive walk to the right side of the
// history tree will all be previous roots from linking right. The last
// node of the left and right traversal will each become a child of the new
// root.
history = new this.Node();
root = this.root;
while (true) {
var comparison = this.contentCompare(value, root.value);
if (comparison < 0) {
if (root.left) {
if (this.contentCompare(value, root.left.value) < 0) {
// rotate right
// Root L(temp)
// / \ / \
// L(temp) R LL Root
// / \ / \
// LL LR LR R
temp = root.left;
root.left = temp.right;
root.touch();
temp.right = root;
temp.touch();
root = temp;
if (!root.left) {
break;
}
}
// remember former root for repropagating length
temp = new Node();
temp.right = root;
temp.left = history.left;
history.left = temp;
// link left
right.left = root;
right.touch();
right = root;
root = root.left;
} else {
break;
}
} else if (comparison > 0) {
if (root.right) {
if (this.contentCompare(value, root.right.value) > 0) {
// rotate left
// Root L(temp)
// / \ / \
// L(temp) R LL Root
// / \ / \
// LL LR LR R
temp = root.right;
root.right = temp.left;
root.touch();
temp.left = root;
temp.touch();
root = temp;
if (!root.right) {
break;
}
}
// remember former root for repropagating length
temp = new Node();
temp.left = root;
temp.right = history.right;
history.right = temp;
// link right
left.right = root;
left.touch();
left = root;
root = root.right;
} else {
break;
}
} else { // equal or incomparable
break;
}
}
// reassemble
left.right = root.left;
left.touch();
right.left = root.right;
right.touch();
root.left = stub.right;
root.right = stub.left;
// propagate new lengths
while (history.left) {
history.left.right.touch();
history.left = history.left.left;
}
while (history.right) {
history.right.left.touch();
history.right = history.right.right;
}
root.touch();
this.root = root;
};
// an internal utility for splaying a node based on its index
SortedSet.prototype.splayIndex = function (index) {
if (this.root) {
var at = this.root;
var atIndex = this.root.index;
while (atIndex !== index) {
if (atIndex > index && at.left) {
at = at.left;
atIndex -= 1 + (at.right ? at.right.length : 0);
} else if (atIndex < index && at.right) {
at = at.right;
atIndex += 1 + (at.left ? at.left.length : 0);
} else {
break;
}
}
this.splay(at.value);
return this.root.index === index;
}
return false;
};
SortedSet.prototype.reduce = function (callback, basis, thisp) {
if (this.root) {
basis = this.root.reduce(callback, basis, 0, thisp, this);
}
return basis;
};
SortedSet.prototype.reduceRight = function (callback, basis, thisp) {
if (this.root) {
basis = this.root.reduceRight(callback, basis, this.length - 1, thisp, this);
}
return basis;
};
SortedSet.prototype.min = function (at) {
var least = this.findLeast(at);
if (least) {
return least.value;
}
};
SortedSet.prototype.max = function (at) {
var greatest = this.findGreatest(at);
if (greatest) {
return greatest.value;
}
};
SortedSet.prototype.one = function () {
return this.min();
};
SortedSet.prototype.clear = function () {
var minus;
if (this.dispatchesRangeChanges) {
minus = this.toArray();
this.dispatchBeforeRangeChange([], minus, 0);
}
this.root = null;
this.length = 0;
if (this.dispatchesRangeChanges) {
this.dispatchRangeChange([], minus, 0);
}
};
SortedSet.prototype.iterate = function (start, end) {
return new this.Iterator(this, start, end);
};
SortedSet.prototype.Iterator = Iterator;
SortedSet.prototype.summary = function () {
if (this.root) {
return this.root.summary();
} else {
return "()";
}
};
SortedSet.prototype.log = function (charmap, logNode, callback, thisp) {
charmap = charmap || TreeLog.unicodeRound;
logNode = logNode || this.logNode;
if (!callback) {
callback = console.log;
thisp = console;
}
callback = callback.bind(thisp);
if (this.root) {
this.root.log(charmap, logNode, callback, callback);
}
};
SortedSet.prototype.logNode = function (node, log, logBefore) {
log(" " + node.value);
};
SortedSet.logCharsets = TreeLog;
SortedSet.prototype.Node = Node;
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
this.length = 1;
}
// TODO case where no basis is provided for reduction
Node.prototype.reduce = function (callback, basis, index, thisp, tree, depth) {
depth = depth || 0;
if (this.left) {
// prerecord length to be resistant to mutation
var length = this.left.length;
basis = this.left.reduce(callback, basis, index, thisp, tree, depth + 1);
index += length;
}
basis = callback.call(thisp, basis, this.value, index, tree, this, depth);
index += 1;
if (this.right) {
basis = this.right.reduce(callback, basis, index, thisp, tree, depth + 1);
}
return basis;
};
Node.prototype.reduceRight = function (callback, basis, index, thisp, tree, depth) {
depth = depth || 0;
if (this.right) {
basis = this.right.reduceRight(callback, basis, index, thisp, tree, depth + 1);
index -= this.right.length;
}
basis = callback.call(thisp, basis, this.value, this.value, tree, this, depth);
index -= 1;
if (this.left) {
basis = this.left.reduceRight(callback, basis, index, thisp, tree, depth + 1);
}
return basis;
};
Node.prototype.touch = function () {
this.length = 1 +
(this.left ? this.left.length : 0) +
(this.right ? this.right.length : 0);
this.index = this.left ? this.left.length : 0;
};
Node.prototype.checkIntegrity = function () {
var length = 1;
length += this.left ? this.left.checkIntegrity() : 0;
length += this.right ? this.right.checkIntegrity() : 0;
if (this.length !== length)
throw new Error("Integrity check failed: " + this.summary());
return length;
}
// get the next node in this subtree
Node.prototype.getNext = function () {
var node = this;
if (node.right) {
node = node.right;
while (node.left) {
node = node.left;
}
return node;
}
};
// get the previous node in this subtree
Node.prototype.getPrevious = function () {
var node = this;
if (node.left) {
node = node.left;
while (node.right) {
node = node.right;
}
return node;
}
};
Node.prototype.summary = function () {
var value = this.value || "-";
value += " <" + this.length;
if (!this.left && !this.right) {
return "(" + value + ")";
}
return "(" + value + " " + (
this.left ? this.left.summary() : "()"
) + ", " + (
this.right ? this.right.summary() : "()"
) + ")";
};
Node.prototype.log = function (charmap, logNode, log, logAbove) {
var self = this;
var branch;
if (this.left && this.right) {
branch = charmap.intersection;
} else if (this.left) {
branch = charmap.branchUp;
} else if (this.right) {
branch = charmap.branchDown;
} else {
branch = charmap.through;
}
var loggedAbove;
this.left && this.left.log(
charmap,
logNode,
function innerWrite(line) {
if (!loggedAbove) {
loggedAbove = true;
// leader
logAbove(charmap.fromBelow + charmap.through + line);
} else {
// below
logAbove(charmap.strafe + " " + line);
}
},
function innerWriteAbove(line) {
// above
logAbove(" " + line);
}
);
var loggedOn;
logNode(
this,
function innerWrite(line) {
if (!loggedOn) {
loggedOn = true;
log(branch + line);
} else {
log((self.right ? charmap.strafe : " ") + line);
}
},
function innerWriteAbove(line) {
logAbove((self.left ? charmap.strafe : " ") + line);
}
);
var loggedBelow;
this.right && this.right.log(
charmap,
logNode,
function innerWrite(line) {
if (!loggedBelow) {
loggedBelow = true;
log(charmap.fromAbove + charmap.through + line);
} else {
log(" " + line);
}
},
function innerWriteAbove(line) {
log(charmap.strafe + " " + line);
}
);
};
function Iterator(set, start, end) {
this.set = set;
this.prev = null;
this.end = end;
if (start) {
var next = this.set.findLeastGreaterThanOrEqual(start);
if (next) {
this.set.splay(next.value);
this.prev = next.getPrevious();
}
}
}
Iterator.prototype.__iterationObject = null;
Object.defineProperty(Iterator.prototype,"_iterationObject", {
get: function() {
return this.__iterationObject || (this.__iterationObject = { done: false, value:null});
}
});
Iterator.prototype.next = function () {
var next;
if (this.prev) {
next = this.set.findLeastGreaterThan(this.prev.value);
} else {
next = this.set.findLeast();
}
if (!next) {
this._iterationObject.done = true;
this._iterationObject.value = void 0;
}
else {
if (
this.end !== undefined &&
this.set.contentCompare(next.value, this.end) >= 0
) {
this._iterationObject.done = true;
this._iterationObject.value = void 0;
}
else {
this.prev = next;
this._iterationObject.value = next.value;
}
}
return this._iterationObject;
};