atomic-fns 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/.esdoc.json +2 -2
  2. package/README.md +48 -13
  3. package/core/collections/BTree.d.ts +229 -0
  4. package/core/collections/BTree.js +1165 -0
  5. package/core/collections/BTree.ts +1340 -0
  6. package/core/collections/Heap.d.ts +69 -0
  7. package/core/collections/Heap.js +181 -0
  8. package/core/collections/Heap.ts +189 -0
  9. package/core/collections/LRUCache.d.ts +131 -0
  10. package/core/collections/LRUCache.js +388 -0
  11. package/core/collections/LRUCache.ts +465 -0
  12. package/core/collections/SortedMap.d.ts +92 -0
  13. package/core/collections/SortedMap.js +130 -0
  14. package/core/collections/SortedMap.ts +146 -0
  15. package/core/collections/SortedSet.d.ts +63 -0
  16. package/core/collections/SortedSet.js +93 -0
  17. package/core/collections/SortedSet.ts +104 -0
  18. package/core/collections/SortedTree.d.ts +103 -0
  19. package/core/collections/SortedTree.js +141 -0
  20. package/core/collections/SortedTree.ts +160 -0
  21. package/core/collections/SplayTree.d.ts +105 -0
  22. package/core/collections/SplayTree.js +338 -0
  23. package/core/collections/SplayTree.ts +354 -0
  24. package/core/collections/abc.d.ts +152 -0
  25. package/core/collections/abc.js +39 -0
  26. package/core/collections/abc.ts +176 -0
  27. package/core/collections/deque.d.ts +110 -0
  28. package/core/collections/deque.js +285 -0
  29. package/core/collections/deque.ts +329 -0
  30. package/core/collections/frozenset.d.ts +19 -0
  31. package/core/collections/frozenset.js +33 -0
  32. package/core/collections/frozenset.ts +37 -0
  33. package/{src → core}/collections/index.d.ts +41 -162
  34. package/{src → core}/collections/index.js +57 -165
  35. package/{src → core}/collections/index.ts +61 -225
  36. package/core/collections/test.html +10 -0
  37. package/core/collections/typedArrays.d.ts +31 -0
  38. package/core/collections/typedArrays.js +143 -0
  39. package/core/collections/typedArrays.ts +163 -0
  40. package/core/datetime/index.d.ts +45 -0
  41. package/core/datetime/index.js +71 -0
  42. package/core/datetime/index.ts +128 -0
  43. package/{src → core}/functools/index.d.ts +2 -2
  44. package/{src → core}/functools/index.js +2 -2
  45. package/{src → core}/functools/index.ts +2 -2
  46. package/{src → core}/globals/index.d.ts +2 -7
  47. package/{src → core}/globals/index.js +5 -2
  48. package/{src → core}/globals/index.ts +6 -9
  49. package/{src → core}/index.d.ts +0 -1
  50. package/{src → core}/index.js +0 -1
  51. package/{src → core}/index.ts +0 -1
  52. package/{src → core}/itertools/index.d.ts +9 -7
  53. package/{src → core}/itertools/index.js +25 -9
  54. package/{src → core}/itertools/index.ts +39 -16
  55. package/{src → core}/math/index.d.ts +0 -0
  56. package/{src → core}/math/index.js +0 -0
  57. package/{src → core}/math/index.ts +0 -0
  58. package/core/operators/index.d.ts +148 -0
  59. package/core/operators/index.js +271 -0
  60. package/core/operators/index.ts +282 -0
  61. package/{src → core}/random/index.d.ts +0 -0
  62. package/{src → core}/random/index.js +0 -0
  63. package/{src → core}/random/index.ts +0 -0
  64. package/package.json +6 -6
  65. package/tests/BTree.spec.ts +143 -0
  66. package/tests/Cache.spec.ts +161 -0
  67. package/tests/Heap.spec.ts +66 -0
  68. package/tests/SortedMap.spec.ts +144 -0
  69. package/tests/SortedSet.spec.ts +84 -0
  70. package/tests/SortedTree.spec.ts +164 -0
  71. package/tests/SplayTree.spec.ts +121 -0
  72. package/tests/collections.spec.ts +1 -1
  73. package/tests/deque.spec.ts +107 -0
  74. package/tests/globals.spec.ts +2 -2
  75. package/tests/itertools.spec.ts +2 -2
  76. package/tests/math.spec.ts +1 -1
  77. package/tests/operators.spec.ts +5 -5
  78. package/tests/random.spec.ts +10 -10
  79. package/tsconfig.json +10 -10
  80. package/tsconfig.node.json +2 -2
  81. package/tsconfig.xo.json +2 -2
  82. package/src/datetime/index.d.ts +0 -6
  83. package/src/datetime/index.js +0 -6
  84. package/src/datetime/index.ts +0 -7
  85. package/src/operators/index.d.ts +0 -31
  86. package/src/operators/index.js +0 -171
  87. package/src/operators/index.ts +0 -175
@@ -0,0 +1,1165 @@
1
+ import { KeyError } from '../globals/index.js';
2
+ import { compare } from '../operators/index.js';
3
+ import { Mapping } from './abc.js';
4
+ const Delete = { delete: true };
5
+ const DeleteRange = () => Delete;
6
+ const Break = { break: true };
7
+ const EmptyArray = [];
8
+ const ReusedArray = []; // assumed thread-local
9
+ // Optimization: this array of `undefined`s is used instead of a normal
10
+ // array of values in nodes where `undefined` is the only value.
11
+ // Its length is extended to max node size on first use; since it can
12
+ // be shared between trees with different maximums, its length can only
13
+ // increase, never decrease. Its type should be undefined[] but strangely
14
+ // TypeScript won't allow the comparison V[] === undefined[]. To prevent
15
+ // users from making this array too large, BTree has a maximum node size.
16
+ //
17
+ // FAQ: undefVals[i] is already undefined, so why increase the array size?
18
+ // Reading outside the bounds of an array is relatively slow because it
19
+ // has the side effect of scanning the prototype chain.
20
+ const undefVals = [];
21
+ /**
22
+ * Leaf nodes and base class for internals.
23
+ * Based on the `sorted-btree` implementation by David Piepgrass (MIT License).
24
+ * @private
25
+ */
26
+ class BNode {
27
+ // If this is an internal node, _keys[i] is the highest key in children[i].
28
+ keys;
29
+ values;
30
+ // True if this node might be within multiple `BTree`s (or have multiple parents).
31
+ // If so, it must be cloned before being mutated to avoid changing an unrelated tree.
32
+ // This is transitive: if it's true, children are also shared even if `isShared!=true`
33
+ // in those children. (Certain operations will propagate isShared=true to children.)
34
+ isShared;
35
+ get isLeaf() {
36
+ return this.children === undefined;
37
+ }
38
+ constructor(keys = [], values) {
39
+ this.keys = keys;
40
+ this.values = values || undefVals;
41
+ this.isShared = undefined;
42
+ }
43
+ /// ////////////////////////////////////////////////////////////////////////
44
+ // Shared methods /////////////////////////////////////////////////////////
45
+ maxKey() {
46
+ return this.keys[this.keys.length - 1];
47
+ }
48
+ // If key not found, returns i^failXor where i is the insertion index.
49
+ // Callers that don't care whether there was a match will set failXor=0.
50
+ indexOf(key, failXor, cmp) {
51
+ const keys = this.keys;
52
+ let lo = 0;
53
+ let hi = keys.length;
54
+ let mid = hi >> 1;
55
+ while (lo < hi) {
56
+ const c = cmp(keys[mid], key);
57
+ if (c < 0)
58
+ lo = mid + 1;
59
+ else if (c > 0)
60
+ hi = mid; // key < keys[mid]
61
+ else if (c === 0)
62
+ return mid;
63
+ else {
64
+ // c is NaN or otherwise invalid
65
+ // eslint-disable-next-line
66
+ if (key === key)
67
+ // at least the search key is not NaN
68
+ return keys.length;
69
+ // eslint-disable-next-line
70
+ else
71
+ throw new KeyError(`Btree found an invalid key: ${key}`);
72
+ }
73
+ mid = (lo + hi) >> 1;
74
+ }
75
+ return mid ^ failXor;
76
+ }
77
+ /// //////////////////////////////////////////////////////////////////////////
78
+ // Leaf Node: misc //////////////////////////////////////////////////////////
79
+ minKey() {
80
+ return this.keys[0];
81
+ }
82
+ minPair(reusedArray) {
83
+ if (this.keys.length === 0)
84
+ return undefined;
85
+ reusedArray[0] = this.keys[0];
86
+ reusedArray[1] = this.values[0];
87
+ return reusedArray;
88
+ }
89
+ maxPair(reusedArray) {
90
+ if (this.keys.length === 0)
91
+ return undefined;
92
+ const lastIndex = this.keys.length - 1;
93
+ reusedArray[0] = this.keys[lastIndex];
94
+ reusedArray[1] = this.values[lastIndex];
95
+ return reusedArray;
96
+ }
97
+ clone() {
98
+ const v = this.values;
99
+ return new BNode(this.keys.slice(0), v === undefVals ? v : v.slice(0));
100
+ }
101
+ greedyClone(force) {
102
+ return this.isShared && !force ? this : this.clone();
103
+ }
104
+ get(key, defaultValue, tree) {
105
+ const i = this.indexOf(key, -1, tree._compare);
106
+ return i < 0 ? defaultValue : this.values[i];
107
+ }
108
+ getPairOrNextLower(key, compare, inclusive, reusedArray) {
109
+ const i = this.indexOf(key, -1, compare);
110
+ const indexOrLower = i < 0 ? ~i - 1 : inclusive ? i : i - 1;
111
+ if (indexOrLower >= 0) {
112
+ reusedArray[0] = this.keys[indexOrLower];
113
+ reusedArray[1] = this.values[indexOrLower];
114
+ return reusedArray;
115
+ }
116
+ return undefined;
117
+ }
118
+ getPairOrNextHigher(key, compare, inclusive, reusedArray) {
119
+ const i = this.indexOf(key, -1, compare);
120
+ const indexOrLower = i < 0 ? ~i : inclusive ? i : i + 1;
121
+ const keys = this.keys;
122
+ if (indexOrLower < keys.length) {
123
+ reusedArray[0] = keys[indexOrLower];
124
+ reusedArray[1] = this.values[indexOrLower];
125
+ return reusedArray;
126
+ }
127
+ return undefined;
128
+ }
129
+ checkValid(depth, tree, baseIndex) {
130
+ const kL = this.keys.length;
131
+ const vL = this.values.length;
132
+ assert(this.values === undefVals ? kL <= vL : kL === vL, 'keys/values length mismatch: depth', depth, 'with lengths', kL, vL, 'and baseIndex', baseIndex);
133
+ // Note: we don't check for "node too small" because sometimes a node
134
+ // can legitimately have size 1. This occurs if there is a batch
135
+ // deletion, leaving a node of size 1, and the siblings are full so
136
+ // it can't be merged with adjacent nodes. However, the parent will
137
+ // verify that the average node size is at least half of the maximum.
138
+ assert(depth === 0 || kL > 0, 'empty leaf at depth', depth, 'and baseIndex', baseIndex);
139
+ return kL;
140
+ }
141
+ /// //////////////////////////////////////////////////////////////////////////
142
+ // Leaf Node: set & node splitting //////////////////////////////////////////
143
+ set(key, value, overwrite, tree) {
144
+ let i = this.indexOf(key, -1, tree._compare);
145
+ if (i < 0) {
146
+ // key does not exist yet
147
+ i = ~i;
148
+ tree.count++;
149
+ if (this.keys.length < tree._maxNodeSize) {
150
+ return this.insertInLeaf(i, key, value, tree);
151
+ }
152
+ else {
153
+ // This leaf node is full and must split
154
+ const newRightSibling = this.splitOffRightSide();
155
+ // eslint-disable-next-line
156
+ let target = this;
157
+ if (i > this.keys.length) {
158
+ i -= this.keys.length;
159
+ target = newRightSibling;
160
+ }
161
+ target.insertInLeaf(i, key, value, tree);
162
+ return newRightSibling;
163
+ }
164
+ }
165
+ else {
166
+ // Key already exists
167
+ if (overwrite !== false) {
168
+ if (value !== undefined)
169
+ this.reifyValues();
170
+ // usually this is a no-op, but some users may wish to edit the key
171
+ this.keys[i] = key;
172
+ this.values[i] = value;
173
+ }
174
+ return false;
175
+ }
176
+ }
177
+ reifyValues() {
178
+ if (this.values === undefVals)
179
+ return (this.values = this.values.slice(0, this.keys.length));
180
+ return this.values;
181
+ }
182
+ insertInLeaf(i, key, value, tree) {
183
+ this.keys.splice(i, 0, key);
184
+ if (this.values === undefVals) {
185
+ while (undefVals.length < tree._maxNodeSize)
186
+ undefVals.push(undefined);
187
+ if (value === undefined) {
188
+ return true;
189
+ }
190
+ else {
191
+ this.values = undefVals.slice(0, this.keys.length - 1);
192
+ }
193
+ }
194
+ this.values.splice(i, 0, value);
195
+ return true;
196
+ }
197
+ takeFromRight(rhs) {
198
+ // Reminder: parent node must update its copy of key for this node
199
+ // assert: neither node is shared
200
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
201
+ let v = this.values;
202
+ if (rhs.values === undefVals) {
203
+ if (v !== undefVals)
204
+ v.push(undefined);
205
+ }
206
+ else {
207
+ v = this.reifyValues();
208
+ // eslint-disable-next-line
209
+ v.push(rhs.values.shift());
210
+ }
211
+ // eslint-disable-next-line
212
+ this.keys.push(rhs.keys.shift());
213
+ }
214
+ takeFromLeft(lhs) {
215
+ // Reminder: parent node must update its copy of key for this node
216
+ // assert: neither node is shared
217
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
218
+ let v = this.values;
219
+ if (lhs.values === undefVals) {
220
+ if (v !== undefVals)
221
+ v.unshift();
222
+ }
223
+ else {
224
+ v = this.reifyValues();
225
+ // eslint-disable-next-line
226
+ v.unshift(lhs.values.pop());
227
+ }
228
+ // eslint-disable-next-line
229
+ this.keys.unshift(lhs.keys.pop());
230
+ }
231
+ splitOffRightSide() {
232
+ // Reminder: parent node must update its copy of key for this node
233
+ const half = this.keys.length >> 1;
234
+ const keys = this.keys.splice(half);
235
+ const values = this.values === undefVals ? undefVals : this.values.splice(half);
236
+ return new BNode(keys, values);
237
+ }
238
+ /// //////////////////////////////////////////////////////////////////////////
239
+ // Leaf Node: scanning & deletions //////////////////////////////////////////
240
+ forRange(low, high, includeHigh, editMode, tree, count, onFound) {
241
+ const cmp = tree._compare;
242
+ let iLow, iHigh;
243
+ if (high === low) {
244
+ if (!includeHigh)
245
+ return count;
246
+ iHigh = (iLow = this.indexOf(low, -1, cmp)) + 1;
247
+ if (iLow < 0)
248
+ return count;
249
+ }
250
+ else {
251
+ iLow = this.indexOf(low, 0, cmp);
252
+ iHigh = this.indexOf(high, -1, cmp);
253
+ if (iHigh < 0)
254
+ iHigh = ~iHigh;
255
+ else if (includeHigh === true)
256
+ iHigh++;
257
+ }
258
+ const keys = this.keys;
259
+ const values = this.values;
260
+ if (onFound !== undefined) {
261
+ for (let i = iLow; i < iHigh; i++) {
262
+ const key = keys[i];
263
+ const result = onFound(key, values[i], count++);
264
+ if (result !== undefined) {
265
+ if (editMode) {
266
+ if (key !== keys[i] || this.isShared === true)
267
+ throw new Error('BTree illegally changed or cloned in editRange');
268
+ if (result.delete) {
269
+ this.keys.splice(i, 1);
270
+ if (this.values !== undefVals)
271
+ this.values.splice(i, 1);
272
+ tree.count--;
273
+ i--;
274
+ iHigh--;
275
+ }
276
+ else if (result.value) {
277
+ values[i] = result.value;
278
+ }
279
+ }
280
+ if (result.break !== undefined)
281
+ return result;
282
+ }
283
+ }
284
+ }
285
+ else
286
+ count += iHigh - iLow;
287
+ return count;
288
+ }
289
+ /** Adds entire contents of right-hand sibling (rhs is left unchanged) */
290
+ mergeSibling(rhs, _) {
291
+ this.keys.push.apply(this.keys, rhs.keys);
292
+ if (this.values === undefVals) {
293
+ if (rhs.values === undefVals)
294
+ return;
295
+ this.values = this.values.slice(0, this.keys.length);
296
+ }
297
+ this.values.push.apply(this.values, rhs.reifyValues());
298
+ }
299
+ }
300
+ const EmptyLeaf = new BNode();
301
+ EmptyLeaf.isShared = true;
302
+ function assert(exp, ...args) {
303
+ if (!exp) {
304
+ args.unshift('B+ tree'); // at beginning of message
305
+ throw new Error(args.join(' '));
306
+ }
307
+ }
308
+ export class BTree extends Mapping {
309
+ root = EmptyLeaf;
310
+ count = 0;
311
+ _maxNodeSize;
312
+ /**
313
+ * provides a total order over keys (and a strict partial order over the type K)
314
+ * @returns a negative value if a < b, 0 if a === b and a positive value if a > b
315
+ */
316
+ _compare;
317
+ /**
318
+ * Initializes an empty B+ tree.
319
+ * @param {?Iterable<[K, V]>} [entries] The initial key value pairs.
320
+ * @param compareFn Custom function to compare pairs of elements in the tree.
321
+ * If not specified, defaultComparator will be used which is valid as long as K extends DefaultComparable.
322
+ * @param entries A set of key-value pairs to initialize the tree
323
+ * @param {number} [maxNodeSize=64] Branching factor (maximum items or children per node)
324
+ * Must be in range 4..256. If undefined or <4 then default is used; if >256 then 256.
325
+ */
326
+ constructor(entries, compareFn, maxNodeSize = 64) {
327
+ super();
328
+ this._maxNodeSize = maxNodeSize >= 4 ? Math.min(maxNodeSize, 256) : 64;
329
+ this._compare = compareFn || compare;
330
+ if (entries)
331
+ this.extend(entries);
332
+ }
333
+ /** Gets the number of key-value pairs in the tree. */
334
+ get size() {
335
+ return this.count;
336
+ }
337
+ /** Releases the tree so that its size is 0. */
338
+ clear() {
339
+ this.root = EmptyLeaf;
340
+ this.count = 0;
341
+ }
342
+ // /** Runs a function for each key-value pair, in order from smallest to
343
+ // * largest key. For compatibility with ES6 Map, the argument order to
344
+ // * the callback is backwards: value first, then key. Call forEachPair
345
+ // * instead to receive the key as the first argument.
346
+ // * @returns the number of values that were sent to the callback,
347
+ // * or the R value if the callback returned {break:R}. */
348
+ // forEach<R = number>(iteratee: Iteratee<V, K>): R | number {
349
+ // return this.forEachPair((k, v) => iteratee(v as V, k, this))
350
+ // }
351
+ // /** Runs a function for each key-value pair, in order from smallest to
352
+ // * largest key. The callback can return {break:R} (where R is any value
353
+ // * except undefined) to stop immediately and return R from forEachPair.
354
+ // * @param onFound A function that is called for each key-value pair. This
355
+ // * function can return {break:R} to stop early with result R.
356
+ // * The reason that you must return {break:R} instead of simply R
357
+ // * itself is for consistency with editRange(), which allows
358
+ // * multiple actions, not just breaking.
359
+ // * @param initialCounter This is the value of the third argument of
360
+ // * `onFound` the first time it is called. The counter increases
361
+ // * by one each time `onFound` is called. Default value: 0
362
+ // * @returns the number of pairs sent to the callback (plus initialCounter,
363
+ // * if you provided one). If the callback returned {break:R} then
364
+ // * the R value is returned instead. */
365
+ // private forEachPair<R = number>(callback: Iteratee<K, V>, initialCounter?: number): R | number {
366
+ // const low = this.minKey()
367
+ // const high = this.maxKey()
368
+ // // eslint-disable-next-line
369
+ // return this.rangeForEach(low!, high, true, callback, initialCounter)
370
+ // }
371
+ /**
372
+ * Finds a pair in the tree and returns the associated value.
373
+ * @param defaultValue a value to return if the key was not found.
374
+ * @returns the value, or defaultValue if the key was not found.
375
+ * @description Computational complexity: O(log size)
376
+ */
377
+ get(key, defaultValue) {
378
+ return this.root.get(key, defaultValue, this);
379
+ }
380
+ /**
381
+ * Adds or overwrites a key-value pair in the B+ tree.
382
+ * @param key the key is used to determine the sort order of
383
+ * data in the tree.
384
+ * @param value data to associate with the key (optional)
385
+ * @returns true if a new key-value pair was added.
386
+ * @description Computational complexity: O(log size)
387
+ * Note: when overwriting a previous entry, the key is updated
388
+ * as well as the value. This has no effect unless the new key
389
+ * has data that does not affect its sort order.
390
+ */
391
+ set(key, value) {
392
+ if (this.root.isShared)
393
+ this.root = this.root.clone();
394
+ const result = this.root.set(key, value, true, this);
395
+ if (result === true || result === false)
396
+ return result;
397
+ // Root node has split, so create a new root node.
398
+ this.root = new BNodeInternal([this.root, result]);
399
+ return true;
400
+ }
401
+ add(key) {
402
+ return this.set(key, null);
403
+ }
404
+ /**
405
+ * Returns true if the key exists in the B+ tree, false if not.
406
+ * @param key Key to detect
407
+ * @description Computational complexity: O(log size)
408
+ */
409
+ contains(key) {
410
+ return this.get(key) !== undefined;
411
+ }
412
+ /**
413
+ * Removes a single key-value pair from the B+ tree.
414
+ * @param key Key to find
415
+ * @returns true if a pair was found and removed, false otherwise.
416
+ * @description Computational complexity: O(log size)
417
+ */
418
+ remove(key) {
419
+ return this.rangeUpdate(key, key, true, DeleteRange) !== 0;
420
+ }
421
+ /** Returns an iterator that provides items in order (ascending order if
422
+ * the collection's comparator uses ascending order, as is the default.)
423
+ * @param lowestKey First key to be iterated, or undefined to start at
424
+ * minKey(). If the specified key doesn't exist then iteration
425
+ * starts at the next higher key (according to the comparator).
426
+ * @param reusedArray Optional array used repeatedly to store key-value
427
+ * pairs, to avoid creating a new array on every iteration.
428
+ */
429
+ entries(lowestKey, reusedArray) {
430
+ const info = this.findPath(lowestKey);
431
+ if (info === undefined)
432
+ return iterator();
433
+ let { nodequeue, nodeindex, leaf } = info;
434
+ let state = reusedArray !== undefined ? 1 : 0;
435
+ let i = lowestKey === undefined ? -1 : leaf.indexOf(lowestKey, 0, this._compare) - 1;
436
+ return iterator(() => {
437
+ // eslint-disable-next-line
438
+ jump: while (true) {
439
+ switch (state) {
440
+ case 0:
441
+ if (++i < leaf.keys.length)
442
+ return { done: false, value: [leaf.keys[i], leaf.values[i]] };
443
+ state = 2;
444
+ continue;
445
+ case 1:
446
+ if (++i < leaf.keys.length) {
447
+ // eslint-disable-next-line
448
+ reusedArray[0] = leaf.keys[i];
449
+ // eslint-disable-next-line
450
+ reusedArray[1] = leaf.values[i];
451
+ return { done: false, value: reusedArray };
452
+ }
453
+ state = 2;
454
+ // eslint-disable-next-line
455
+ case 2:
456
+ // Advance to the next leaf node
457
+ // eslint-disable-next-line
458
+ let level = -1;
459
+ while (true) {
460
+ if (++level >= nodequeue.length) {
461
+ state = 3;
462
+ // eslint-disable-next-line
463
+ continue jump;
464
+ }
465
+ if (++nodeindex[level] < nodequeue[level].length)
466
+ break;
467
+ }
468
+ for (; level > 0; level--) {
469
+ nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
470
+ nodeindex[level - 1] = 0;
471
+ }
472
+ leaf = nodequeue[0][nodeindex[0]];
473
+ i = -1;
474
+ state = reusedArray !== undefined ? 1 : 0;
475
+ continue;
476
+ case 3:
477
+ return { done: true, value: undefined };
478
+ }
479
+ }
480
+ });
481
+ }
482
+ /** Returns an iterator that provides items in reversed order.
483
+ * @param highestKey Key at which to start iterating, or undefined to
484
+ * start at maxKey(). If the specified key doesn't exist then iteration
485
+ * starts at the next lower key (according to the comparator).
486
+ * @param reusedArray Optional array used repeatedly to store key-value
487
+ * pairs, to avoid creating a new array on every iteration.
488
+ * @param skipHighest Iff this flag is true and the highestKey exists in the
489
+ * collection, the pair matching highestKey is skipped, not iterated.
490
+ */
491
+ reversed(highestKey, reusedArray, skipHighest) {
492
+ if (highestKey === undefined) {
493
+ highestKey = this.maxKey();
494
+ skipHighest = undefined;
495
+ if (highestKey === undefined)
496
+ return iterator(); // collection is empty
497
+ }
498
+ // eslint-disable-next-line
499
+ let { nodequeue, nodeindex, leaf } = this.findPath(highestKey) || this.findPath(this.maxKey());
500
+ assert(!nodequeue[0] || leaf === nodequeue[0][nodeindex[0]], 'wat!');
501
+ let i = leaf.indexOf(highestKey, 0, this._compare);
502
+ if (!skipHighest && i < leaf.keys.length && this._compare(leaf.keys[i], highestKey) <= 0)
503
+ i++;
504
+ let state = reusedArray !== undefined ? 1 : 0;
505
+ return iterator(() => {
506
+ // eslint-disable-next-line
507
+ jump: while (true) {
508
+ switch (state) {
509
+ case 0:
510
+ if (--i >= 0)
511
+ return { done: false, value: [leaf.keys[i], leaf.values[i]] };
512
+ state = 2;
513
+ continue;
514
+ case 1:
515
+ if (--i >= 0) {
516
+ // eslint-disable-next-line
517
+ reusedArray[0] = leaf.keys[i];
518
+ // eslint-disable-next-line
519
+ reusedArray[1] = leaf.values[i];
520
+ return { done: false, value: reusedArray };
521
+ }
522
+ state = 2;
523
+ // eslint-disable-next-line
524
+ case 2:
525
+ // Advance to the next leaf node
526
+ // eslint-disable-next-line
527
+ let level = -1;
528
+ while (true) {
529
+ if (++level >= nodequeue.length) {
530
+ state = 3;
531
+ // eslint-disable-next-line
532
+ continue jump;
533
+ }
534
+ if (--nodeindex[level] >= 0)
535
+ break;
536
+ }
537
+ for (; level > 0; level--) {
538
+ nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
539
+ nodeindex[level - 1] = nodequeue[level - 1].length - 1;
540
+ }
541
+ leaf = nodequeue[0][nodeindex[0]];
542
+ i = leaf.keys.length;
543
+ state = reusedArray !== undefined ? 1 : 0;
544
+ continue;
545
+ case 3:
546
+ return { done: true, value: undefined };
547
+ }
548
+ }
549
+ });
550
+ }
551
+ /* Used by entries() and entriesReversed() to prepare to start iterating.
552
+ * It develops a "node queue" for each non-leaf level of the tree.
553
+ * Levels are numbered "bottom-up" so that level 0 is a list of leaf
554
+ * nodes from a low-level non-leaf node. The queue at a given level L
555
+ * consists of nodequeue[L] which is the children of a BNodeInternal,
556
+ * and nodeindex[L], the current index within that child list, such
557
+ * such that nodequeue[L-1] === nodequeue[L][nodeindex[L]].children.
558
+ * (However inside this function the order is reversed.)
559
+ * @private
560
+ */
561
+ findPath(key) {
562
+ let nextnode = this.root;
563
+ let nodequeue, nodeindex;
564
+ if (nextnode.isLeaf) {
565
+ // use preallocated empty
566
+ nodequeue = EmptyArray;
567
+ nodeindex = EmptyArray;
568
+ }
569
+ else {
570
+ nodequeue = [];
571
+ nodeindex = [];
572
+ for (let d = 0; !nextnode.isLeaf; d++) {
573
+ nodequeue[d] = nextnode.children;
574
+ nodeindex[d] = key === undefined ? 0 : nextnode.indexOf(key, 0, this._compare);
575
+ if (nodeindex[d] >= nodequeue[d].length)
576
+ return; // first key > maxKey()
577
+ nextnode = nodequeue[d][nodeindex[d]];
578
+ }
579
+ nodequeue.reverse();
580
+ nodeindex.reverse();
581
+ }
582
+ return { nodequeue, nodeindex, leaf: nextnode };
583
+ }
584
+ /** Returns a new iterator for iterating the keys of each pair in ascending order.
585
+ * @param firstKey: Minimum key to include in the output. */
586
+ keys(firstKey) {
587
+ const it = this.entries(firstKey, ReusedArray);
588
+ return iterator(() => {
589
+ const n = it.next();
590
+ if (n.value)
591
+ n.value = n.value[0];
592
+ return n;
593
+ });
594
+ }
595
+ /** Gets the lowest key in the tree. Complexity: O(log size) */
596
+ minKey() {
597
+ return this.root.minKey();
598
+ }
599
+ /** Gets the highest key in the tree. Complexity: O(1) */
600
+ maxKey() {
601
+ return this.root.maxKey();
602
+ }
603
+ /** Returns a new iterator for iterating the values of each pair in order by key.
604
+ * @param firstKey: Minimum key whose associated value is included in the output. */
605
+ values(firstKey) {
606
+ const it = this.entries(firstKey, ReusedArray);
607
+ return iterator(() => {
608
+ const n = it.next();
609
+ if (n.value)
610
+ n.value = n.value[1];
611
+ return n;
612
+ });
613
+ }
614
+ /// //////////////////////////////////////////////////////////////////////////
615
+ // Additional methods ///////////////////////////////////////////////////////
616
+ /** Returns the maximum number of children/values before nodes will split. */
617
+ get maxNodeSize() {
618
+ return this._maxNodeSize;
619
+ }
620
+ // /** Quickly clones the tree by marking the root node as shared.
621
+ // * Both copies remain editable. When you modify either copy, any
622
+ // * nodes that are shared (or potentially shared) between the two
623
+ // * copies are cloned so that the changes do not affect other copies.
624
+ // * This is known as copy-on-write behavior, or "lazy copying". */
625
+ // clone(): BTree<K, V> {
626
+ // this.root.isShared = true
627
+ // let result = new BTree<K, V>(undefined, this._compare, this._maxNodeSize)
628
+ // result.root = this.root
629
+ // result.count = this.count
630
+ // return result
631
+ // }
632
+ /** Performs a deep cloning of the tree, immediately duplicating any nodes that are
633
+ * not currently marked as shared, in order to avoid marking any
634
+ * additional nodes as shared.
635
+ * @param force Clone all nodes, even shared ones.
636
+ */
637
+ clone(force = false) {
638
+ const result = new BTree(undefined, this._compare, this._maxNodeSize);
639
+ result.root = this.root.greedyClone(force);
640
+ result.count = this.count;
641
+ return result;
642
+ }
643
+ /** Gets an array filled with the contents of the tree, sorted by key */
644
+ toArray() {
645
+ const min = this.minKey();
646
+ const max = this.maxKey();
647
+ const maxLength = 2147483647;
648
+ if (min !== undefined)
649
+ return this.keysRange(min, max, true, maxLength);
650
+ return [];
651
+ }
652
+ /** Gets a string representing the tree's data based on toArray(). */
653
+ toString() {
654
+ return this.toArray().toString();
655
+ }
656
+ /** Returns the next pair whose key is larger than the specified key (or undefined if there is none).
657
+ * If key === undefined, this function returns the lowest pair.
658
+ * @param key The key to search for.
659
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
660
+ * avoid creating a new array on every iteration.
661
+ */
662
+ lowerBound(key, reusedArray) {
663
+ reusedArray = reusedArray || [];
664
+ if (key === undefined) {
665
+ return this.root.minPair(reusedArray);
666
+ }
667
+ return this.root.getPairOrNextHigher(key, this._compare, false, reusedArray);
668
+ }
669
+ /** Returns the next key larger than the specified key, or undefined if there is none.
670
+ * Also, nextHigherKey(undefined) returns the lowest key.
671
+ */
672
+ // nextHigherKey(key: K | undefined): K | undefined {
673
+ // let p = this.after(key, ReusedArray as [K, V])
674
+ // return p && p[0]
675
+ // }
676
+ /** Returns the next pair whose key is smaller than the specified key (or undefined if there is none).
677
+ * If key === undefined, this function returns the highest pair.
678
+ * @param key The key to search for.
679
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
680
+ * avoid creating a new array each time you call this method.
681
+ */
682
+ upperBound(key, reusedArray) {
683
+ reusedArray = reusedArray || [];
684
+ if (key === undefined) {
685
+ return this.root.maxPair(reusedArray);
686
+ }
687
+ return this.root.getPairOrNextLower(key, this._compare, false, reusedArray);
688
+ }
689
+ /** Returns the next key smaller than the specified key, or undefined if there is none.
690
+ * Also, nextLowerKey(undefined) returns the highest key.
691
+ */
692
+ // nextLowerKey(key: K | undefined): K | undefined {
693
+ // let p = this.before(key, ReusedArray as [K, V])
694
+ // return p && p[0]
695
+ // }
696
+ /** Returns the key-value pair associated with the supplied key if it exists
697
+ * or the pair associated with the next lower pair otherwise. If there is no
698
+ * next lower pair, undefined is returned.
699
+ * @param key The key to search for.
700
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
701
+ * avoid creating a new array each time you call this method.
702
+ * */
703
+ floor(key, reusedArray) {
704
+ return this.root.getPairOrNextLower(key, this._compare, true, reusedArray || []);
705
+ }
706
+ /** Returns the key-value pair associated with the supplied key if it exists
707
+ * or the pair associated with the next lower pair otherwise. If there is no
708
+ * next lower pair, undefined is returned.
709
+ * @param key The key to search for.
710
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
711
+ * avoid creating a new array each time you call this method.
712
+ * */
713
+ ceiling(key, reusedArray) {
714
+ return this.root.getPairOrNextHigher(key, this._compare, true, reusedArray || []);
715
+ }
716
+ /**
717
+ * Builds an array of pairs from the specified range of keys, sorted by key.
718
+ * Each returned pair is also an array: pair[0] is the key, pair[1] is the value.
719
+ * @param low The first key in the array will be greater than or equal to `low`.
720
+ * @param high This method returns when a key larger than this is reached.
721
+ * @param includeHigh If the `high` key is present, its pair will be included
722
+ * in the output if and only if this parameter is true. Note: if the
723
+ * `low` key is present, it is always included in the output.
724
+ * @param maxLength Length limit. getRange will stop scanning the tree when
725
+ * the array reaches this size.
726
+ * @description Computational complexity: O(result.length + log size)
727
+ */
728
+ keysRange(low, high, includeHigh, maxLength = 0x3ffffff) {
729
+ const results = [];
730
+ this.root.forRange(low, high, includeHigh, false, this, 0, (k, v) => {
731
+ results.push([k, v]);
732
+ return results.length > maxLength ? Break : undefined;
733
+ });
734
+ return results;
735
+ }
736
+ /** Adds all pairs from a list of key-value pairs.
737
+ * @param entries Pairs to add to this tree. If there are duplicate keys,
738
+ * later pairs currently overwrite earlier ones (e.g. [[0,1],[0,7]]
739
+ * associates 0 with 7.)
740
+ * @returns The number of pairs added to the collection.
741
+ * @description Computational complexity: O(pairs.length * log(size + pairs.length))
742
+ */
743
+ extend(entries) {
744
+ let added = 0;
745
+ for (const pair of entries) {
746
+ this.set(pair[0], pair[1] ?? null);
747
+ added++;
748
+ }
749
+ return added;
750
+ }
751
+ /**
752
+ * Scans the specified range of keys, in ascending order by key.
753
+ * Note: the callback `onFound` must not insert or remove items in the
754
+ * collection. Doing so may cause incorrect data to be sent to the
755
+ * callback afterward.
756
+ * @param low The first key scanned will be greater than or equal to `low`.
757
+ * @param high Scanning stops when a key larger than this is reached.
758
+ * @param includeHigh If the `high` key is present, `onFound` is called for
759
+ * that final pair if and only if this parameter is true.
760
+ * @param onFound A function that is called for each key-value pair. This
761
+ * function can return {break:R} to stop early with result R.
762
+ * @param initialCounter Initial third argument of onFound. This value
763
+ * increases by one each time `onFound` is called. Default: 0
764
+ * @returns The number of values found, or R if the callback returned
765
+ * `{break:R}` to stop early.
766
+ * @description Computational complexity: O(number of items scanned + log size)
767
+ */
768
+ rangeForEach(low, high, includeHigh, onFound, initialCounter) {
769
+ const r = this.root.forRange(low, high, includeHigh, false, this, initialCounter || 0, onFound);
770
+ return typeof r === 'number' ? r : r.break;
771
+ }
772
+ /**
773
+ * Scans and potentially modifies values for a subsequence of keys.
774
+ * Note: the callback `onFound` should ideally be a pure function.
775
+ * Specifically, it must not insert items, call clone(), or change
776
+ * the collection except via return value; out-of-band editing may
777
+ * cause an exception or may cause incorrect data to be sent to
778
+ * the callback (duplicate or missed items). It must not cause a
779
+ * clone() of the collection, otherwise the clone could be modified
780
+ * by changes requested by the callback.
781
+ * @param low The first key scanned will be greater than or equal to `low`.
782
+ * @param high Scanning stops when a key larger than this is reached.
783
+ * @param includeHigh If the `high` key is present, `onFound` is called for
784
+ * that final pair if and only if this parameter is true.
785
+ * @param onFound A function that is called for each key-value pair. This
786
+ * function can return `{value:v}` to change the value associated
787
+ * with the current key, `{delete:true}` to delete the current pair,
788
+ * `{break:R}` to stop early with result R, or it can return nothing
789
+ * (undefined or {}) to cause no effect and continue iterating.
790
+ * `{break:R}` can be combined with one of the other two commands.
791
+ * The third argument `counter` is the number of items iterated
792
+ * previously; it equals 0 when `onFound` is called the first time.
793
+ * @returns The number of values scanned, or R if the callback returned
794
+ * `{break:R}` to stop early.
795
+ * @description
796
+ * Computational complexity: O(number of items scanned + log size)
797
+ * Note: if the tree has been cloned with clone(), any shared
798
+ * nodes are copied before `onFound` is called. This takes O(n) time
799
+ * where n is proportional to the amount of shared data scanned.
800
+ */
801
+ rangeUpdate(low, high, includeHigh, onFound, initialCounter) {
802
+ let root = this.root;
803
+ if (root.isShared)
804
+ this.root = root = root.clone();
805
+ try {
806
+ const r = root.forRange(low, high, includeHigh, true, this, initialCounter || 0, onFound);
807
+ return typeof r === 'number' ? r : r.break;
808
+ }
809
+ finally {
810
+ let isShared;
811
+ while (root.keys.length <= 1 && !root.isLeaf) {
812
+ isShared ||= root.isShared;
813
+ this.root = root =
814
+ root.keys.length === 0 ? EmptyLeaf : root.children[0];
815
+ }
816
+ // If any ancestor of the new root was shared, the new root must also be shared
817
+ if (isShared) {
818
+ root.isShared = true;
819
+ }
820
+ }
821
+ }
822
+ /**
823
+ * Removes a range of key-value pairs from the B+ tree.
824
+ * @param low The first key scanned will be greater than or equal to `low`.
825
+ * @param high Scanning stops when a key larger than this is reached.
826
+ * @param includeHigh Specifies whether the `high` key, if present, is deleted.
827
+ * @returns The number of key-value pairs that were deleted.
828
+ * @description Computational complexity: O(log size + number of items deleted)
829
+ */
830
+ removeRange(low, high, includeHigh) {
831
+ return this.rangeUpdate(low, high, includeHigh, DeleteRange);
832
+ }
833
+ /** Removes a series of keys from the collection. */
834
+ removeKeys(keys) {
835
+ let r = 0;
836
+ for (let i = 0; i < keys.length; i++)
837
+ if (this.remove(keys[i]))
838
+ r++;
839
+ return r;
840
+ }
841
+ /** Gets the height of the tree: the number of internal nodes between the
842
+ * BTree object and its leaf nodes (zero if there are no internal nodes). */
843
+ get height() {
844
+ let node = this.root;
845
+ let height = -1;
846
+ while (node) {
847
+ height++;
848
+ node = node.isLeaf ? undefined : node?.children?.[0];
849
+ }
850
+ return height;
851
+ }
852
+ /** Makes the object read-only to ensure it is not accidentally modified.
853
+ * Freezing does not have to be permanent; unfreeze() reverses the effect.
854
+ * This is accomplished by replacing mutator functions with a function
855
+ * that throws an Error. Compared to using a property (e.g. this.isFrozen)
856
+ * this implementation gives better performance in non-frozen BTrees.
857
+ */
858
+ freeze() {
859
+ const t = this;
860
+ // Note: all other mutators ultimately call set() or editRange()
861
+ // so we don't need to override those others.
862
+ t.clear =
863
+ t.set =
864
+ t.editRange =
865
+ () => {
866
+ throw TypeError('Attempted to modify a frozen BTree');
867
+ };
868
+ }
869
+ [Symbol.iterator]() {
870
+ return this.entries();
871
+ }
872
+ }
873
+ function iterator(next = () => ({ done: true, value: undefined })) {
874
+ return {
875
+ next,
876
+ [Symbol.iterator]() {
877
+ return this;
878
+ }
879
+ };
880
+ }
881
+ /** Internal node (non-leaf node) ********************************************/
882
+ class BNodeInternal extends BNode {
883
+ // Note: conventionally B+ trees have one fewer key than the number of
884
+ // children, but I find it easier to keep the array lengths equal: each
885
+ // keys[i] caches the value of children[i].maxKey().
886
+ children;
887
+ /**
888
+ * This does not mark `children` as shared, so it is the responsibility of the caller
889
+ * to ensure children are either marked shared, or aren't included in another tree.
890
+ */
891
+ constructor(children, keys) {
892
+ if (!keys) {
893
+ keys = [];
894
+ for (let i = 0; i < children.length; i++)
895
+ keys[i] = children[i].maxKey();
896
+ }
897
+ super(keys);
898
+ this.children = children;
899
+ }
900
+ clone() {
901
+ const children = this.children.slice(0);
902
+ for (let i = 0; i < children.length; i++)
903
+ children[i].isShared = true;
904
+ return new BNodeInternal(children, this.keys.slice(0));
905
+ }
906
+ greedyClone(force) {
907
+ if (this.isShared && !force)
908
+ return this;
909
+ const nu = new BNodeInternal(this.children.slice(0), this.keys.slice(0));
910
+ for (let i = 0; i < nu.children.length; i++)
911
+ nu.children[i] = nu.children[i].greedyClone(force);
912
+ return nu;
913
+ }
914
+ minKey() {
915
+ return this.children[0].minKey();
916
+ }
917
+ minPair(reusedArray) {
918
+ return this.children[0].minPair(reusedArray);
919
+ }
920
+ maxPair(reusedArray) {
921
+ return this.children[this.children.length - 1].maxPair(reusedArray);
922
+ }
923
+ get(key, defaultValue, tree) {
924
+ const i = this.indexOf(key, 0, tree._compare);
925
+ const children = this.children;
926
+ return i < children.length ? children[i].get(key, defaultValue, tree) : undefined;
927
+ }
928
+ getPairOrNextLower(key, compare, inclusive, reusedArray) {
929
+ const i = this.indexOf(key, 0, compare);
930
+ const children = this.children;
931
+ if (i >= children.length)
932
+ return this.maxPair(reusedArray);
933
+ const result = children[i].getPairOrNextLower(key, compare, inclusive, reusedArray);
934
+ if (result === undefined && i > 0) {
935
+ return children[i - 1].maxPair(reusedArray);
936
+ }
937
+ return result;
938
+ }
939
+ getPairOrNextHigher(key, compare, inclusive, reusedArray) {
940
+ const i = this.indexOf(key, 0, compare);
941
+ const children = this.children;
942
+ const length = children.length;
943
+ if (i >= length)
944
+ return undefined;
945
+ const result = children[i].getPairOrNextHigher(key, compare, inclusive, reusedArray);
946
+ if (result === undefined && i < length - 1) {
947
+ return children[i + 1].minPair(reusedArray);
948
+ }
949
+ return result;
950
+ }
951
+ checkValid(depth, tree, baseIndex) {
952
+ const kL = this.keys.length;
953
+ const cL = this.children.length;
954
+ assert(kL === cL, 'keys/children length mismatch: depth', depth, 'lengths', kL, cL, 'baseIndex', baseIndex);
955
+ assert(kL > 1 || depth > 0, 'internal node has length', kL, 'at depth', depth, 'baseIndex', baseIndex);
956
+ let size = 0;
957
+ const c = this.children;
958
+ const k = this.keys;
959
+ let childSize = 0;
960
+ for (let i = 0; i < cL; i++) {
961
+ size += c[i].checkValid(depth + 1, tree, baseIndex + size);
962
+ childSize += c[i].keys.length;
963
+ assert(size >= childSize, 'wtf', baseIndex); // no way this will ever fail
964
+ assert(i === 0 || c[i - 1].constructor === c[i].constructor, 'type mismatch, baseIndex:', baseIndex);
965
+ if (c[i].maxKey() !== k[i])
966
+ assert(false, 'keys[', i, '] =', k[i], 'is wrong, should be ', c[i].maxKey(), 'at depth', depth, 'baseIndex', baseIndex);
967
+ if (!(i === 0 || tree._compare(k[i - 1], k[i]) < 0))
968
+ assert(false, 'sort violation at depth', depth, 'index', i, 'keys', k[i - 1], k[i]);
969
+ }
970
+ // 2020/08: BTree doesn't always avoid grossly undersized nodes,
971
+ // but AFAIK such nodes are pretty harmless, so accept them.
972
+ const toofew = childSize === 0; // childSize < (tree.maxNodeSize >> 1)*cL;
973
+ if (toofew || childSize > tree.maxNodeSize * cL)
974
+ assert(false, toofew ? 'too few' : 'too many', 'children (', childSize, size, ') at depth', depth, 'maxNodeSize:', tree.maxNodeSize, 'children.length:', cL, 'baseIndex:', baseIndex);
975
+ return size;
976
+ }
977
+ /// //////////////////////////////////////////////////////////////////////////
978
+ // Internal Node: set & node splitting //////////////////////////////////////
979
+ set(key, value, overwrite, tree) {
980
+ const c = this.children;
981
+ const max = tree._maxNodeSize;
982
+ const cmp = tree._compare;
983
+ let i = Math.min(this.indexOf(key, 0, cmp), c.length - 1);
984
+ let child = c[i];
985
+ if (child.isShared)
986
+ c[i] = child = child.clone();
987
+ if (child.keys.length >= max) {
988
+ // child is full; inserting anything else will cause a split.
989
+ // Shifting an item to the left or right sibling may avoid a split.
990
+ // We can do a shift if the adjacent node is not full and if the
991
+ // current key can still be placed in the same node after the shift.
992
+ let other;
993
+ if (i > 0 && (other = c[i - 1]).keys.length < max && cmp(child.keys[0], key) < 0) {
994
+ if (other.isShared)
995
+ c[i - 1] = other = other.clone();
996
+ other.takeFromRight(child);
997
+ this.keys[i - 1] = other.maxKey();
998
+ }
999
+ else if ((other = c[i + 1]) !== undefined &&
1000
+ other.keys.length < max &&
1001
+ cmp(child.maxKey(), key) < 0) {
1002
+ if (other.isShared)
1003
+ c[i + 1] = other = other.clone();
1004
+ other.takeFromLeft(child);
1005
+ this.keys[i] = c[i].maxKey();
1006
+ }
1007
+ }
1008
+ const result = child.set(key, value, overwrite, tree);
1009
+ if (result === false)
1010
+ return false;
1011
+ this.keys[i] = child.maxKey();
1012
+ if (result === true)
1013
+ return true;
1014
+ // The child has split and `result` is a new right child... does it fit?
1015
+ if (this.keys.length < max) {
1016
+ // yes
1017
+ this.insert(i + 1, result);
1018
+ return true;
1019
+ }
1020
+ else {
1021
+ // no, we must split also
1022
+ const newRightSibling = this.splitOffRightSide();
1023
+ let target = this;
1024
+ if (cmp(result.maxKey(), this.maxKey()) > 0) {
1025
+ target = newRightSibling;
1026
+ i -= this.keys.length;
1027
+ }
1028
+ target.insert(i + 1, result);
1029
+ return newRightSibling;
1030
+ }
1031
+ }
1032
+ /**
1033
+ * Inserts `child` at index `i`.
1034
+ * This does not mark `child` as shared, so it is the responsibility of the caller
1035
+ * to ensure that either child is marked shared, or it is not included in another tree.
1036
+ */
1037
+ insert(i, child) {
1038
+ this.children.splice(i, 0, child);
1039
+ this.keys.splice(i, 0, child.maxKey());
1040
+ }
1041
+ /**
1042
+ * Split this node.
1043
+ * Modifies this to remove the second half of the items, returning a separate node containing them.
1044
+ */
1045
+ splitOffRightSide() {
1046
+ // assert !this.isShared;
1047
+ const half = this.children.length >> 1;
1048
+ return new BNodeInternal(this.children.splice(half), this.keys.splice(half));
1049
+ }
1050
+ takeFromRight(rhs) {
1051
+ // Reminder: parent node must update its copy of key for this node
1052
+ // assert: neither node is shared
1053
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
1054
+ // eslint-disable-next-line
1055
+ this.keys.push(rhs.keys.shift());
1056
+ // eslint-disable-next-line
1057
+ this.children.push(rhs.children.shift());
1058
+ }
1059
+ takeFromLeft(lhs) {
1060
+ // Reminder: parent node must update its copy of key for this node
1061
+ // assert: neither node is shared
1062
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
1063
+ // eslint-disable-next-line
1064
+ this.keys.unshift(lhs.keys.pop());
1065
+ // eslint-disable-next-line
1066
+ this.children.unshift(lhs.children.pop());
1067
+ }
1068
+ /// //////////////////////////////////////////////////////////////////////////
1069
+ // Internal Node: scanning & deletions //////////////////////////////////////
1070
+ // Note: `count` is the next value of the third argument to `onFound`.
1071
+ // A leaf node's `forRange` function returns a new value for this counter,
1072
+ // unless the operation is to stop early.
1073
+ forRange(low, high, includeHigh, editMode, tree, count, onFound) {
1074
+ const cmp = tree._compare;
1075
+ const keys = this.keys;
1076
+ const children = this.children;
1077
+ let iLow = this.indexOf(low, 0, cmp);
1078
+ let i = iLow;
1079
+ const iHigh = Math.min(high === low ? iLow : this.indexOf(high, 0, cmp), keys.length - 1);
1080
+ if (!editMode) {
1081
+ // Simple case
1082
+ for (; i <= iHigh; i++) {
1083
+ const result = children[i].forRange(low, high, includeHigh, editMode, tree, count, onFound);
1084
+ if (typeof result !== 'number')
1085
+ return result;
1086
+ count = result;
1087
+ }
1088
+ }
1089
+ else if (i <= iHigh) {
1090
+ try {
1091
+ for (; i <= iHigh; i++) {
1092
+ if (children[i].isShared)
1093
+ children[i] = children[i].clone();
1094
+ const result = children[i].forRange(low, high, includeHigh, editMode, tree, count, onFound);
1095
+ // Note: if children[i] is empty then keys[i]=undefined.
1096
+ // This is an invalid state, but it is fixed below.
1097
+ keys[i] = children[i].maxKey();
1098
+ if (typeof result !== 'number')
1099
+ return result;
1100
+ count = result;
1101
+ }
1102
+ }
1103
+ finally {
1104
+ // Deletions may have occurred, so look for opportunities to merge nodes.
1105
+ const half = tree._maxNodeSize >> 1;
1106
+ if (iLow > 0)
1107
+ iLow--;
1108
+ for (i = iHigh; i >= iLow; i--) {
1109
+ if (children[i].keys.length <= half) {
1110
+ if (children[i].keys.length !== 0) {
1111
+ this.tryMerge(i, tree._maxNodeSize);
1112
+ }
1113
+ else {
1114
+ // child is empty! delete it!
1115
+ keys.splice(i, 1);
1116
+ children.splice(i, 1);
1117
+ }
1118
+ }
1119
+ }
1120
+ if (children.length !== 0 && children[0].keys.length === 0)
1121
+ assert(false, 'emptiness bug');
1122
+ }
1123
+ }
1124
+ return count;
1125
+ }
1126
+ /** Merges child i with child i+1 if their combined size is not too large */
1127
+ tryMerge(i, maxSize) {
1128
+ const children = this.children;
1129
+ if (i >= 0 && i + 1 < children.length) {
1130
+ if (children[i].keys.length + children[i + 1].keys.length <= maxSize) {
1131
+ if (children[i].isShared)
1132
+ // cloned already UNLESS i is outside scan range
1133
+ children[i] = children[i].clone();
1134
+ children[i].mergeSibling(children[i + 1], maxSize);
1135
+ children.splice(i + 1, 1);
1136
+ this.keys.splice(i + 1, 1);
1137
+ this.keys[i] = children[i].maxKey();
1138
+ return true;
1139
+ }
1140
+ }
1141
+ return false;
1142
+ }
1143
+ /**
1144
+ * Move children from `rhs` into this.
1145
+ * `rhs` must be part of this tree, and be removed from it after this call
1146
+ * (otherwise isShared for its children could be incorrect).
1147
+ */
1148
+ mergeSibling(rhs, maxNodeSize) {
1149
+ // assert !this.isShared;
1150
+ const oldLength = this.keys.length;
1151
+ this.keys.push.apply(this.keys, rhs.keys);
1152
+ const rhsChildren = rhs.children;
1153
+ this.children.push.apply(this.children, rhsChildren);
1154
+ if (rhs.isShared && !this.isShared) {
1155
+ // All children of a shared node are implicitly shared, and since their new
1156
+ // parent is not shared, they must now be explicitly marked as shared.
1157
+ for (let i = 0; i < rhsChildren.length; i++)
1158
+ rhsChildren[i].isShared = true;
1159
+ }
1160
+ // If our children are themselves almost empty due to a mass-delete,
1161
+ // they may need to be merged too (but only the oldLength-1 and its
1162
+ // right sibling should need this).
1163
+ this.tryMerge(oldLength - 1, maxNodeSize);
1164
+ }
1165
+ }