btree-core 3.2.1

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 (42) hide show
  1. package/LICENSE +23 -0
  2. package/b+tree.d.ts +429 -0
  3. package/b+tree.js +1545 -0
  4. package/b+tree.min.js +1 -0
  5. package/extended/bulkLoad.d.ts +14 -0
  6. package/extended/bulkLoad.js +113 -0
  7. package/extended/bulkLoad.min.js +1 -0
  8. package/extended/decompose.d.ts +1 -0
  9. package/extended/decompose.js +680 -0
  10. package/extended/decompose.min.js +1 -0
  11. package/extended/diffAgainst.d.ts +23 -0
  12. package/extended/diffAgainst.js +254 -0
  13. package/extended/diffAgainst.min.js +1 -0
  14. package/extended/forEachKeyInBoth.d.ts +19 -0
  15. package/extended/forEachKeyInBoth.js +73 -0
  16. package/extended/forEachKeyInBoth.min.js +1 -0
  17. package/extended/forEachKeyNotIn.d.ts +18 -0
  18. package/extended/forEachKeyNotIn.js +87 -0
  19. package/extended/forEachKeyNotIn.min.js +1 -0
  20. package/extended/index.d.ts +133 -0
  21. package/extended/index.js +200 -0
  22. package/extended/index.min.js +1 -0
  23. package/extended/intersect.d.ts +16 -0
  24. package/extended/intersect.js +44 -0
  25. package/extended/intersect.min.js +1 -0
  26. package/extended/parallelWalk.d.ts +1 -0
  27. package/extended/parallelWalk.js +188 -0
  28. package/extended/parallelWalk.min.js +1 -0
  29. package/extended/shared.d.ts +1 -0
  30. package/extended/shared.js +64 -0
  31. package/extended/shared.min.js +1 -0
  32. package/extended/subtract.d.ts +16 -0
  33. package/extended/subtract.js +35 -0
  34. package/extended/subtract.min.js +1 -0
  35. package/extended/union.d.ts +16 -0
  36. package/extended/union.js +36 -0
  37. package/extended/union.min.js +1 -0
  38. package/interfaces.d.ts +307 -0
  39. package/package.json +122 -0
  40. package/readme.md +420 -0
  41. package/sorted-array.d.ts +22 -0
  42. package/sorted-array.js +71 -0
package/b+tree.js ADDED
@@ -0,0 +1,1545 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.EmptyBTree = exports.check = exports.areOverlapping = exports.sumChildSizes = exports.BNodeInternal = exports.BNode = exports.asSet = exports.fixMaxSize = exports.simpleComparator = exports.defaultComparator = void 0;
19
+ /**
20
+ * Compares DefaultComparables to form a strict partial ordering.
21
+ *
22
+ * Handles +/-0 and NaN like Map: NaN is equal to NaN, and -0 is equal to +0.
23
+ *
24
+ * Arrays are compared using '<' and '>', which may cause unexpected equality:
25
+ * for example [1] will be considered equal to ['1'].
26
+ *
27
+ * Two objects with equal valueOf compare the same, but compare unequal to
28
+ * primitives that have the same value.
29
+ */
30
+ function defaultComparator(a, b) {
31
+ // Special case finite numbers first for performance.
32
+ // Note that the trick of using 'a - b' and checking for NaN to detect non-numbers
33
+ // does not work if the strings are numeric (ex: "5"). This would leading most
34
+ // comparison functions using that approach to fail to have transitivity.
35
+ if (Number.isFinite(a) && Number.isFinite(b)) {
36
+ return a - b;
37
+ }
38
+ // The default < and > operators are not totally ordered. To allow types to be mixed
39
+ // in a single collection, compare types and order values of different types by type.
40
+ var ta = typeof a;
41
+ var tb = typeof b;
42
+ if (ta !== tb) {
43
+ return ta < tb ? -1 : 1;
44
+ }
45
+ if (ta === 'object') {
46
+ // standardized JavaScript bug: null is not an object, but typeof says it is
47
+ if (a === null)
48
+ return b === null ? 0 : -1;
49
+ else if (b === null)
50
+ return 1;
51
+ a = a.valueOf();
52
+ b = b.valueOf();
53
+ ta = typeof a;
54
+ tb = typeof b;
55
+ // Deal with the two valueOf()s producing different types
56
+ if (ta !== tb) {
57
+ return ta < tb ? -1 : 1;
58
+ }
59
+ }
60
+ // a and b are now the same type, and will be a number, string or array
61
+ // (which we assume holds numbers or strings), or something unsupported.
62
+ if (a < b)
63
+ return -1;
64
+ if (a > b)
65
+ return 1;
66
+ if (a === b)
67
+ return 0;
68
+ // Order NaN less than other numbers
69
+ if (Number.isNaN(a))
70
+ return Number.isNaN(b) ? 0 : -1;
71
+ else if (Number.isNaN(b))
72
+ return 1;
73
+ // This could be two objects (e.g. [7] and ['7']) that aren't ordered
74
+ return Array.isArray(a) ? 0 : Number.NaN;
75
+ }
76
+ exports.defaultComparator = defaultComparator;
77
+ ;
78
+ function simpleComparator(a, b) {
79
+ return a > b ? 1 : a < b ? -1 : 0;
80
+ }
81
+ exports.simpleComparator = simpleComparator;
82
+ ;
83
+ /** Sanitizes a requested max node size.
84
+ * @internal */
85
+ function fixMaxSize(maxNodeSize) {
86
+ return maxNodeSize >= 4 ? Math.min(maxNodeSize | 0, 256) : 32;
87
+ }
88
+ exports.fixMaxSize = fixMaxSize;
89
+ /**
90
+ * A reasonably fast collection of key-value pairs with a powerful API.
91
+ * Largely compatible with the standard Map. BTree is a B+ tree data structure,
92
+ * so the collection is sorted by key.
93
+ *
94
+ * B+ trees tend to use memory more efficiently than hashtables such as the
95
+ * standard Map, especially when the collection contains a large number of
96
+ * items. However, maintaining the sort order makes them modestly slower:
97
+ * O(log size) rather than O(1). This B+ tree implementation supports O(1)
98
+ * fast cloning. It also supports freeze(), which can be used to ensure that
99
+ * a BTree is not changed accidentally.
100
+ *
101
+ * Confusingly, the ES6 Map.forEach(c) method calls c(value,key) instead of
102
+ * c(key,value), in contrast to other methods such as set() and entries()
103
+ * which put the key first. I can only assume that the order was reversed on
104
+ * the theory that users would usually want to examine values and ignore keys.
105
+ * BTree's forEach() therefore works the same way, but a second method
106
+ * `.forEachPair((key,value)=>{...})` is provided which sends you the key
107
+ * first and the value second; this method is slightly faster because it is
108
+ * the "native" for-each method for this class.
109
+ *
110
+ * Out of the box, BTree supports keys that are numbers, strings, arrays of
111
+ * numbers/strings, Date, and objects that have a valueOf() method returning a
112
+ * number or string. Other data types, such as arrays of Date or custom
113
+ * objects, require a custom comparator, which you must pass as the second
114
+ * argument to the constructor (the first argument is an optional list of
115
+ * initial items). Symbols cannot be used as keys because they are unordered
116
+ * (one Symbol is never "greater" or "less" than another).
117
+ *
118
+ * @example
119
+ * Given a {name: string, age: number} object, you can create a tree sorted by
120
+ * name and then by age like this:
121
+ *
122
+ * var tree = new BTree(undefined, (a, b) => {
123
+ * if (a.name > b.name)
124
+ * return 1; // Return a number >0 when a > b
125
+ * else if (a.name < b.name)
126
+ * return -1; // Return a number <0 when a < b
127
+ * else // names are equal (or incomparable)
128
+ * return a.age - b.age; // Return >0 when a.age > b.age
129
+ * });
130
+ *
131
+ * tree.set({name:"Bill", age:17}, "happy");
132
+ * tree.set({name:"Fran", age:40}, "busy & stressed");
133
+ * tree.set({name:"Bill", age:55}, "recently laid off");
134
+ * tree.forEachPair((k, v) => {
135
+ * console.log(`Name: ${k.name} Age: ${k.age} Status: ${v}`);
136
+ * });
137
+ *
138
+ * @description
139
+ * The "range" methods (`forEach, forRange, editRange`) will return the number
140
+ * of elements that were scanned. In addition, the callback can return {break:R}
141
+ * to stop early and return R from the outer function.
142
+ *
143
+ * - TODO: Test performance of preallocating values array at max size
144
+ * - TODO: Add fast initialization when a sorted array is provided to constructor
145
+ *
146
+ * For more documentation see https://github.com/qwertie/btree-typescript
147
+ *
148
+ * Are you a C# developer? You might like the similar data structures I made for C#:
149
+ * BDictionary, BList, etc. See http://core.loyc.net/collections/
150
+ *
151
+ * @author David Piepgrass
152
+ */
153
+ var BTree = /** @class */ (function () {
154
+ /**
155
+ * Initializes an empty B+ tree.
156
+ * @param compare Custom function to compare pairs of elements in the tree.
157
+ * If not specified, defaultComparator will be used which is valid as long as K extends DefaultComparable.
158
+ * @param entries A set of key-value pairs to initialize the tree
159
+ * @param maxNodeSize Branching factor (maximum items or children per node)
160
+ * Must be in range 4..256. If undefined or <4 then default is used; if >256 then 256.
161
+ */
162
+ function BTree(entries, compare, maxNodeSize) {
163
+ this._root = EmptyLeaf;
164
+ this._maxNodeSize = fixMaxSize(maxNodeSize);
165
+ this._compare = compare || defaultComparator;
166
+ if (entries)
167
+ this.setPairs(entries);
168
+ }
169
+ Object.defineProperty(BTree.prototype, "size", {
170
+ /////////////////////////////////////////////////////////////////////////////
171
+ // ES6 Map<K,V> methods /////////////////////////////////////////////////////
172
+ /** Gets the number of key-value pairs in the tree. */
173
+ get: function () { return this._root.size(); },
174
+ enumerable: false,
175
+ configurable: true
176
+ });
177
+ Object.defineProperty(BTree.prototype, "length", {
178
+ /** Gets the number of key-value pairs in the tree. */
179
+ get: function () { return this.size; },
180
+ enumerable: false,
181
+ configurable: true
182
+ });
183
+ Object.defineProperty(BTree.prototype, "isEmpty", {
184
+ /** Returns true iff the tree contains no key-value pairs. */
185
+ get: function () { return this._root.size() === 0; },
186
+ enumerable: false,
187
+ configurable: true
188
+ });
189
+ /** Releases the tree so that its size is 0. */
190
+ BTree.prototype.clear = function () {
191
+ this._root = EmptyLeaf;
192
+ };
193
+ /** Runs a function for each key-value pair, in order from smallest to
194
+ * largest key. For compatibility with ES6 Map, the argument order to
195
+ * the callback is backwards: value first, then key. Call forEachPair
196
+ * instead to receive the key as the first argument.
197
+ * @param thisArg If provided, this parameter is assigned as the `this`
198
+ * value for each callback.
199
+ * @returns the number of values that were sent to the callback,
200
+ * or the R value if the callback returned {break:R}. */
201
+ BTree.prototype.forEach = function (callback, thisArg) {
202
+ var _this = this;
203
+ if (thisArg !== undefined)
204
+ callback = callback.bind(thisArg);
205
+ return this.forEachPair(function (k, v) { return callback(v, k, _this); });
206
+ };
207
+ /** Runs a function for each key-value pair, in order from smallest to
208
+ * largest key. The callback can return {break:R} (where R is any value
209
+ * except undefined) to stop immediately and return R from forEachPair.
210
+ * @param onFound A function that is called for each key-value pair. This
211
+ * function can return {break:R} to stop early with result R.
212
+ * The reason that you must return {break:R} instead of simply R
213
+ * itself is for consistency with editRange(), which allows
214
+ * multiple actions, not just breaking.
215
+ * @param initialCounter This is the value of the third argument of
216
+ * `onFound` the first time it is called. The counter increases
217
+ * by one each time `onFound` is called. Default value: 0
218
+ * @returns the number of pairs sent to the callback (plus initialCounter,
219
+ * if you provided one). If the callback returned {break:R} then
220
+ * the R value is returned instead. */
221
+ BTree.prototype.forEachPair = function (callback, initialCounter) {
222
+ var low = this.minKey(), high = this.maxKey();
223
+ return this.forRange(low, high, true, callback, initialCounter);
224
+ };
225
+ /**
226
+ * Finds a pair in the tree and returns the associated value.
227
+ * @param defaultValue a value to return if the key was not found.
228
+ * @returns the value, or defaultValue if the key was not found.
229
+ * @description Computational complexity: O(log size)
230
+ */
231
+ BTree.prototype.get = function (key, defaultValue) {
232
+ return this._root.get(key, defaultValue, this);
233
+ };
234
+ /**
235
+ * Adds or overwrites a key-value pair in the B+ tree.
236
+ * @param key the key is used to determine the sort order of
237
+ * data in the tree.
238
+ * @param value data to associate with the key (optional)
239
+ * @param overwrite Whether to overwrite an existing key-value pair
240
+ * (default: true). If this is false and there is an existing
241
+ * key-value pair then this method has no effect.
242
+ * @returns true if a new key-value pair was added.
243
+ * @description Computational complexity: O(log size)
244
+ * Note: when overwriting a previous entry, the key is updated
245
+ * as well as the value. This has no effect unless the new key
246
+ * has data that does not affect its sort order.
247
+ */
248
+ BTree.prototype.set = function (key, value, overwrite) {
249
+ if (this._root.isShared)
250
+ this._root = this._root.clone();
251
+ var result = this._root.set(key, value, overwrite, this);
252
+ if (result === true || result === false)
253
+ return result;
254
+ // Root node has split, so create a new root node.
255
+ var children = [this._root, result];
256
+ this._root = new BNodeInternal(children, sumChildSizes(children));
257
+ return true;
258
+ };
259
+ /**
260
+ * Returns true if the key exists in the B+ tree, false if not.
261
+ * Use get() for best performance; use has() if you need to
262
+ * distinguish between "undefined value" and "key not present".
263
+ * @param key Key to detect
264
+ * @description Computational complexity: O(log size)
265
+ */
266
+ BTree.prototype.has = function (key) {
267
+ return this.forRange(key, key, true, undefined) !== 0;
268
+ };
269
+ /**
270
+ * Removes a single key-value pair from the B+ tree.
271
+ * @param key Key to find
272
+ * @returns true if a pair was found and removed, false otherwise.
273
+ * @description Computational complexity: O(log size)
274
+ */
275
+ BTree.prototype.delete = function (key) {
276
+ return this.editRange(key, key, true, DeleteRange) !== 0;
277
+ };
278
+ BTree.prototype.with = function (key, value, overwrite) {
279
+ var nu = this.clone();
280
+ return nu.set(key, value, overwrite) || overwrite ? nu : this;
281
+ };
282
+ /** Returns a copy of the tree with the specified key-value pairs set. */
283
+ BTree.prototype.withPairs = function (pairs, overwrite) {
284
+ var nu = this.clone();
285
+ return nu.setPairs(pairs, overwrite) !== 0 || overwrite ? nu : this;
286
+ };
287
+ /** Returns a copy of the tree with the specified keys present.
288
+ * @param keys The keys to add. If a key is already present in the tree,
289
+ * neither the existing key nor the existing value is modified.
290
+ * @param returnThisIfUnchanged if true, returns this if all keys already
291
+ * existed. Performance note: due to the architecture of this class, all
292
+ * node(s) leading to existing keys are cloned even if the collection is
293
+ * ultimately unchanged.
294
+ */
295
+ BTree.prototype.withKeys = function (keys, returnThisIfUnchanged) {
296
+ var nu = this.clone(), changed = false;
297
+ for (var i = 0; i < keys.length; i++)
298
+ changed = nu.set(keys[i], undefined, false) || changed;
299
+ return returnThisIfUnchanged && !changed ? this : nu;
300
+ };
301
+ /** Returns a copy of the tree with the specified key removed.
302
+ * @param returnThisIfUnchanged if true, returns this if the key didn't exist.
303
+ * Performance note: due to the architecture of this class, node(s) leading
304
+ * to where the key would have been stored are cloned even when the key
305
+ * turns out not to exist and the collection is unchanged.
306
+ */
307
+ BTree.prototype.without = function (key, returnThisIfUnchanged) {
308
+ return this.withoutRange(key, key, true, returnThisIfUnchanged);
309
+ };
310
+ /** Returns a copy of the tree with the specified keys removed.
311
+ * @param returnThisIfUnchanged if true, returns this if none of the keys
312
+ * existed. Performance note: due to the architecture of this class,
313
+ * node(s) leading to where the key would have been stored are cloned
314
+ * even when the key turns out not to exist.
315
+ */
316
+ BTree.prototype.withoutKeys = function (keys, returnThisIfUnchanged) {
317
+ var nu = this.clone();
318
+ return nu.deleteKeys(keys) || !returnThisIfUnchanged ? nu : this;
319
+ };
320
+ /** Returns a copy of the tree with the specified range of keys removed. */
321
+ BTree.prototype.withoutRange = function (low, high, includeHigh, returnThisIfUnchanged) {
322
+ var nu = this.clone();
323
+ if (nu.deleteRange(low, high, includeHigh) === 0 && returnThisIfUnchanged)
324
+ return this;
325
+ return nu;
326
+ };
327
+ /** Returns a copy of the tree with pairs removed whenever the callback
328
+ * function returns false. `where()` is a synonym for this method. */
329
+ BTree.prototype.filter = function (callback, returnThisIfUnchanged) {
330
+ var nu = this.greedyClone();
331
+ var del;
332
+ nu.editAll(function (k, v, i) {
333
+ if (!callback(k, v, i))
334
+ return del = Delete;
335
+ });
336
+ if (!del && returnThisIfUnchanged)
337
+ return this;
338
+ return nu;
339
+ };
340
+ /** Returns a copy of the tree with all values altered by a callback function. */
341
+ BTree.prototype.mapValues = function (callback) {
342
+ var tmp = {};
343
+ var nu = this.greedyClone();
344
+ nu.editAll(function (k, v, i) {
345
+ return tmp.value = callback(v, k, i), tmp;
346
+ });
347
+ return nu;
348
+ };
349
+ BTree.prototype.reduce = function (callback, initialValue) {
350
+ var i = 0, p = initialValue;
351
+ var it = this.entries(this.minKey(), ReusedArray), next;
352
+ while (!(next = it.next()).done)
353
+ p = callback(p, next.value, i++, this);
354
+ return p;
355
+ };
356
+ /////////////////////////////////////////////////////////////////////////////
357
+ // Iterator methods /////////////////////////////////////////////////////////
358
+ /** Returns an iterator that provides items in order (ascending order if
359
+ * the collection's comparator uses ascending order, as is the default.)
360
+ * @param lowestKey First key to be iterated, or undefined to start at
361
+ * minKey(). If the specified key doesn't exist then iteration
362
+ * starts at the next higher key (according to the comparator).
363
+ * @param reusedArray Optional array used repeatedly to store key-value
364
+ * pairs, to avoid creating a new array on every iteration.
365
+ */
366
+ BTree.prototype.entries = function (lowestKey, reusedArray) {
367
+ var info = this.findPath(lowestKey);
368
+ if (info === undefined)
369
+ return iterator();
370
+ var nodequeue = info.nodequeue, nodeindex = info.nodeindex, leaf = info.leaf;
371
+ var state = reusedArray !== undefined ? 1 : 0;
372
+ var i = (lowestKey === undefined ? -1 : leaf.indexOf(lowestKey, 0, this._compare) - 1);
373
+ return iterator(function () {
374
+ jump: for (;;) {
375
+ switch (state) {
376
+ case 0:
377
+ if (++i < leaf.keys.length)
378
+ return { done: false, value: [leaf.keys[i], leaf.values[i]] };
379
+ state = 2;
380
+ continue;
381
+ case 1:
382
+ if (++i < leaf.keys.length) {
383
+ reusedArray[0] = leaf.keys[i], reusedArray[1] = leaf.values[i];
384
+ return { done: false, value: reusedArray };
385
+ }
386
+ state = 2;
387
+ case 2:
388
+ // Advance to the next leaf node
389
+ for (var level = -1;;) {
390
+ if (++level >= nodequeue.length) {
391
+ state = 3;
392
+ continue jump;
393
+ }
394
+ if (++nodeindex[level] < nodequeue[level].length)
395
+ break;
396
+ }
397
+ for (; level > 0; level--) {
398
+ nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
399
+ nodeindex[level - 1] = 0;
400
+ }
401
+ leaf = nodequeue[0][nodeindex[0]];
402
+ i = -1;
403
+ state = reusedArray !== undefined ? 1 : 0;
404
+ continue;
405
+ case 3:
406
+ return { done: true, value: undefined };
407
+ }
408
+ }
409
+ });
410
+ };
411
+ /** Returns an iterator that provides items in reversed order.
412
+ * @param highestKey Key at which to start iterating, or undefined to
413
+ * start at maxKey(). If the specified key doesn't exist then iteration
414
+ * starts at the next lower key (according to the comparator).
415
+ * @param reusedArray Optional array used repeatedly to store key-value
416
+ * pairs, to avoid creating a new array on every iteration.
417
+ * @param skipHighest Iff this flag is true and the highestKey exists in the
418
+ * collection, the pair matching highestKey is skipped, not iterated.
419
+ */
420
+ BTree.prototype.entriesReversed = function (highestKey, reusedArray, skipHighest) {
421
+ if (highestKey === undefined) {
422
+ highestKey = this.maxKey();
423
+ skipHighest = undefined;
424
+ if (highestKey === undefined)
425
+ return iterator(); // collection is empty
426
+ }
427
+ var _a = this.findPath(highestKey) || this.findPath(this.maxKey()), nodequeue = _a.nodequeue, nodeindex = _a.nodeindex, leaf = _a.leaf;
428
+ check(!nodequeue[0] || leaf === nodequeue[0][nodeindex[0]], "wat!");
429
+ var i = leaf.indexOf(highestKey, 0, this._compare);
430
+ if (!skipHighest && i < leaf.keys.length && this._compare(leaf.keys[i], highestKey) <= 0)
431
+ i++;
432
+ var state = reusedArray !== undefined ? 1 : 0;
433
+ return iterator(function () {
434
+ jump: for (;;) {
435
+ switch (state) {
436
+ case 0:
437
+ if (--i >= 0)
438
+ return { done: false, value: [leaf.keys[i], leaf.values[i]] };
439
+ state = 2;
440
+ continue;
441
+ case 1:
442
+ if (--i >= 0) {
443
+ reusedArray[0] = leaf.keys[i], reusedArray[1] = leaf.values[i];
444
+ return { done: false, value: reusedArray };
445
+ }
446
+ state = 2;
447
+ case 2:
448
+ // Advance to the next leaf node
449
+ for (var level = -1;;) {
450
+ if (++level >= nodequeue.length) {
451
+ state = 3;
452
+ continue jump;
453
+ }
454
+ if (--nodeindex[level] >= 0)
455
+ break;
456
+ }
457
+ for (; level > 0; level--) {
458
+ nodequeue[level - 1] = nodequeue[level][nodeindex[level]].children;
459
+ nodeindex[level - 1] = nodequeue[level - 1].length - 1;
460
+ }
461
+ leaf = nodequeue[0][nodeindex[0]];
462
+ i = leaf.keys.length;
463
+ state = reusedArray !== undefined ? 1 : 0;
464
+ continue;
465
+ case 3:
466
+ return { done: true, value: undefined };
467
+ }
468
+ }
469
+ });
470
+ };
471
+ /* Used by entries() and entriesReversed() to prepare to start iterating.
472
+ * It develops a "node queue" for each non-leaf level of the tree.
473
+ * Levels are numbered "bottom-up" so that level 0 is a list of leaf
474
+ * nodes from a low-level non-leaf node. The queue at a given level L
475
+ * consists of nodequeue[L] which is the children of a BNodeInternal,
476
+ * and nodeindex[L], the current index within that child list, such
477
+ * such that nodequeue[L-1] === nodequeue[L][nodeindex[L]].children.
478
+ * (However inside this function the order is reversed.)
479
+ */
480
+ BTree.prototype.findPath = function (key) {
481
+ var nextnode = this._root;
482
+ var nodequeue, nodeindex;
483
+ if (nextnode.isLeaf) {
484
+ nodequeue = EmptyArray, nodeindex = EmptyArray; // avoid allocations
485
+ }
486
+ else {
487
+ nodequeue = [], nodeindex = [];
488
+ for (var d = 0; !nextnode.isLeaf; d++) {
489
+ nodequeue[d] = nextnode.children;
490
+ nodeindex[d] = key === undefined ? 0 : nextnode.indexOf(key, 0, this._compare);
491
+ if (nodeindex[d] >= nodequeue[d].length)
492
+ return; // first key > maxKey()
493
+ nextnode = nodequeue[d][nodeindex[d]];
494
+ }
495
+ nodequeue.reverse();
496
+ nodeindex.reverse();
497
+ }
498
+ return { nodequeue: nodequeue, nodeindex: nodeindex, leaf: nextnode };
499
+ };
500
+ /** Returns a new iterator for iterating the keys of each pair in ascending order.
501
+ * @param firstKey: Minimum key to include in the output. */
502
+ BTree.prototype.keys = function (firstKey) {
503
+ var it = this.entries(firstKey, ReusedArray);
504
+ return iterator(function () {
505
+ var n = it.next();
506
+ if (n.value)
507
+ n.value = n.value[0];
508
+ return n;
509
+ });
510
+ };
511
+ /** Returns a new iterator for iterating the values of each pair in order by key.
512
+ * @param firstKey: Minimum key whose associated value is included in the output. */
513
+ BTree.prototype.values = function (firstKey) {
514
+ var it = this.entries(firstKey, ReusedArray);
515
+ return iterator(function () {
516
+ var n = it.next();
517
+ if (n.value)
518
+ n.value = n.value[1];
519
+ return n;
520
+ });
521
+ };
522
+ Object.defineProperty(BTree.prototype, "maxNodeSize", {
523
+ /////////////////////////////////////////////////////////////////////////////
524
+ // Additional methods ///////////////////////////////////////////////////////
525
+ /** Returns the maximum number of children/values before nodes will split. */
526
+ get: function () {
527
+ return this._maxNodeSize;
528
+ },
529
+ enumerable: false,
530
+ configurable: true
531
+ });
532
+ /** Gets the lowest key in the tree. Complexity: O(log size) */
533
+ BTree.prototype.minKey = function () { return this._root.minKey(); };
534
+ /** Gets the highest key in the tree. Complexity: O(1) */
535
+ BTree.prototype.maxKey = function () { return this._root.maxKey(); };
536
+ /** Quickly clones the tree by marking the root node as shared.
537
+ * Both copies remain editable. When you modify either copy, any
538
+ * nodes that are shared (or potentially shared) between the two
539
+ * copies are cloned so that the changes do not affect other copies.
540
+ * This is known as copy-on-write behavior, or "lazy copying". */
541
+ BTree.prototype.clone = function () {
542
+ this._root.isShared = true;
543
+ var result = new BTree(undefined, this._compare, this._maxNodeSize);
544
+ result._root = this._root;
545
+ return result;
546
+ };
547
+ /** Performs a greedy clone, immediately duplicating any nodes that are
548
+ * not currently marked as shared, in order to avoid marking any
549
+ * additional nodes as shared.
550
+ * @param force Clone all nodes, even shared ones.
551
+ */
552
+ BTree.prototype.greedyClone = function (force) {
553
+ var result = new BTree(undefined, this._compare, this._maxNodeSize);
554
+ result._root = this._root.greedyClone(force);
555
+ return result;
556
+ };
557
+ /** Gets an array filled with the contents of the tree, sorted by key */
558
+ BTree.prototype.toArray = function (maxLength) {
559
+ if (maxLength === void 0) { maxLength = 0x7FFFFFFF; }
560
+ var min = this.minKey(), max = this.maxKey();
561
+ if (min !== undefined)
562
+ return this.getRange(min, max, true, maxLength);
563
+ return [];
564
+ };
565
+ /** Gets an array of all keys, sorted */
566
+ BTree.prototype.keysArray = function () {
567
+ var results = [];
568
+ this._root.forRange(this.minKey(), this.maxKey(), true, false, this, 0, function (k, v) { results.push(k); });
569
+ return results;
570
+ };
571
+ /** Gets an array of all values, sorted by key */
572
+ BTree.prototype.valuesArray = function () {
573
+ var results = [];
574
+ this._root.forRange(this.minKey(), this.maxKey(), true, false, this, 0, function (k, v) { results.push(v); });
575
+ return results;
576
+ };
577
+ /** Gets a string representing the tree's data based on toArray(). */
578
+ BTree.prototype.toString = function () {
579
+ return this.toArray().toString();
580
+ };
581
+ /** Stores a key-value pair only if the key doesn't already exist in the tree.
582
+ * @returns true if a new key was added
583
+ */
584
+ BTree.prototype.setIfNotPresent = function (key, value) {
585
+ return this.set(key, value, false);
586
+ };
587
+ /** Returns the next pair whose key is larger than the specified key (or undefined if there is none).
588
+ * If key === undefined, this function returns the lowest pair.
589
+ * @param key The key to search for.
590
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
591
+ * avoid creating a new array on every iteration.
592
+ */
593
+ BTree.prototype.nextHigherPair = function (key, reusedArray) {
594
+ reusedArray = reusedArray || [];
595
+ if (key === undefined) {
596
+ return this._root.minPair(reusedArray);
597
+ }
598
+ return this._root.getPairOrNextHigher(key, this._compare, false, reusedArray);
599
+ };
600
+ /** Returns the next key larger than the specified key, or undefined if there is none.
601
+ * Also, nextHigherKey(undefined) returns the lowest key.
602
+ */
603
+ BTree.prototype.nextHigherKey = function (key) {
604
+ var p = this.nextHigherPair(key, ReusedArray);
605
+ return p && p[0];
606
+ };
607
+ /** Returns the next pair whose key is smaller than the specified key (or undefined if there is none).
608
+ * If key === undefined, this function returns the highest pair.
609
+ * @param key The key to search for.
610
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
611
+ * avoid creating a new array each time you call this method.
612
+ */
613
+ BTree.prototype.nextLowerPair = function (key, reusedArray) {
614
+ reusedArray = reusedArray || [];
615
+ if (key === undefined) {
616
+ return this._root.maxPair(reusedArray);
617
+ }
618
+ return this._root.getPairOrNextLower(key, this._compare, false, reusedArray);
619
+ };
620
+ /** Returns the next key smaller than the specified key, or undefined if there is none.
621
+ * Also, nextLowerKey(undefined) returns the highest key.
622
+ */
623
+ BTree.prototype.nextLowerKey = function (key) {
624
+ var p = this.nextLowerPair(key, ReusedArray);
625
+ return p && p[0];
626
+ };
627
+ /** Returns the key-value pair associated with the supplied key if it exists
628
+ * or the pair associated with the next lower pair otherwise. If there is no
629
+ * next lower pair, undefined is returned.
630
+ * @param key The key to search for.
631
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
632
+ * avoid creating a new array each time you call this method.
633
+ * */
634
+ BTree.prototype.getPairOrNextLower = function (key, reusedArray) {
635
+ return this._root.getPairOrNextLower(key, this._compare, true, reusedArray || []);
636
+ };
637
+ /** Returns the key-value pair associated with the supplied key if it exists
638
+ * or the pair associated with the next lower pair otherwise. If there is no
639
+ * next lower pair, undefined is returned.
640
+ * @param key The key to search for.
641
+ * @param reusedArray Optional array used repeatedly to store key-value pairs, to
642
+ * avoid creating a new array each time you call this method.
643
+ * */
644
+ BTree.prototype.getPairOrNextHigher = function (key, reusedArray) {
645
+ return this._root.getPairOrNextHigher(key, this._compare, true, reusedArray || []);
646
+ };
647
+ /** Edits the value associated with a key in the tree, if it already exists.
648
+ * @returns true if the key existed, false if not.
649
+ */
650
+ BTree.prototype.changeIfPresent = function (key, value) {
651
+ return this.editRange(key, key, true, function (k, v) { return ({ value: value }); }) !== 0;
652
+ };
653
+ /**
654
+ * Builds an array of pairs from the specified range of keys, sorted by key.
655
+ * Each returned pair is also an array: pair[0] is the key, pair[1] is the value.
656
+ * @param low The first key in the array will be greater than or equal to `low`.
657
+ * @param high This method returns when a key larger than this is reached.
658
+ * @param includeHigh If the `high` key is present, its pair will be included
659
+ * in the output if and only if this parameter is true. Note: if the
660
+ * `low` key is present, it is always included in the output.
661
+ * @param maxLength Length limit. getRange will stop scanning the tree when
662
+ * the array reaches this size.
663
+ * @description Computational complexity: O(result.length + log size)
664
+ */
665
+ BTree.prototype.getRange = function (low, high, includeHigh, maxLength) {
666
+ if (maxLength === void 0) { maxLength = 0x3FFFFFF; }
667
+ var results = [];
668
+ this._root.forRange(low, high, includeHigh, false, this, 0, function (k, v) {
669
+ results.push([k, v]);
670
+ return results.length > maxLength ? Break : undefined;
671
+ });
672
+ return results;
673
+ };
674
+ /** Adds all pairs from a list of key-value pairs.
675
+ * @param pairs Pairs to add to this tree. If there are duplicate keys,
676
+ * later pairs currently overwrite earlier ones (e.g. [[0,1],[0,7]]
677
+ * associates 0 with 7.)
678
+ * @param overwrite Whether to overwrite pairs that already exist (if false,
679
+ * pairs[i] is ignored when the key pairs[i][0] already exists.)
680
+ * @returns The number of pairs added to the collection.
681
+ * @description Computational complexity: O(pairs.length * log(size + pairs.length))
682
+ */
683
+ BTree.prototype.setPairs = function (pairs, overwrite) {
684
+ var added = 0;
685
+ for (var i = 0; i < pairs.length; i++)
686
+ if (this.set(pairs[i][0], pairs[i][1], overwrite))
687
+ added++;
688
+ return added;
689
+ };
690
+ /**
691
+ * Scans the specified range of keys, in ascending order by key.
692
+ * Note: the callback `onFound` must not insert or remove items in the
693
+ * collection. Doing so may cause incorrect data to be sent to the
694
+ * callback afterward.
695
+ * @param low The first key scanned will be greater than or equal to `low`.
696
+ * @param high Scanning stops when a key larger than this is reached.
697
+ * @param includeHigh If the `high` key is present, `onFound` is called for
698
+ * that final pair if and only if this parameter is true.
699
+ * @param onFound A function that is called for each key-value pair. This
700
+ * function can return {break:R} to stop early with result R.
701
+ * @param initialCounter Initial third argument of onFound. This value
702
+ * increases by one each time `onFound` is called. Default: 0
703
+ * @returns The number of values found, or R if the callback returned
704
+ * `{break:R}` to stop early.
705
+ * @description Computational complexity: O(number of items scanned + log size)
706
+ */
707
+ BTree.prototype.forRange = function (low, high, includeHigh, onFound, initialCounter) {
708
+ var r = this._root.forRange(low, high, includeHigh, false, this, initialCounter || 0, onFound);
709
+ return typeof r === "number" ? r : r.break;
710
+ };
711
+ /**
712
+ * Scans and potentially modifies values for a subsequence of keys.
713
+ * Note: the callback `onFound` should ideally be a pure function.
714
+ * Specfically, it must not insert items, call clone(), or change
715
+ * the collection except via return value; out-of-band editing may
716
+ * cause an exception or may cause incorrect data to be sent to
717
+ * the callback (duplicate or missed items). It must not cause a
718
+ * clone() of the collection, otherwise the clone could be modified
719
+ * by changes requested by the callback.
720
+ * @param low The first key scanned will be greater than or equal to `low`.
721
+ * @param high Scanning stops when a key larger than this is reached.
722
+ * @param includeHigh If the `high` key is present, `onFound` is called for
723
+ * that final pair if and only if this parameter is true.
724
+ * @param onFound A function that is called for each key-value pair. This
725
+ * function can return `{value:v}` to change the value associated
726
+ * with the current key, `{delete:true}` to delete the current pair,
727
+ * `{break:R}` to stop early with result R, or it can return nothing
728
+ * (undefined or {}) to cause no effect and continue iterating.
729
+ * `{break:R}` can be combined with one of the other two commands.
730
+ * The third argument `counter` is the number of items iterated
731
+ * previously; it equals 0 when `onFound` is called the first time.
732
+ * @returns The number of values scanned, or R if the callback returned
733
+ * `{break:R}` to stop early.
734
+ * @description
735
+ * Computational complexity: O(number of items scanned + log size)
736
+ * Note: if the tree has been cloned with clone(), any shared
737
+ * nodes are copied before `onFound` is called. This takes O(n) time
738
+ * where n is proportional to the amount of shared data scanned.
739
+ */
740
+ BTree.prototype.editRange = function (low, high, includeHigh, onFound, initialCounter) {
741
+ var root = this._root;
742
+ if (root.isShared)
743
+ this._root = root = root.clone();
744
+ try {
745
+ var r = root.forRange(low, high, includeHigh, true, this, initialCounter || 0, onFound);
746
+ return typeof r === "number" ? r : r.break;
747
+ }
748
+ finally {
749
+ var isShared = void 0;
750
+ while (root.keys.length <= 1 && !root.isLeaf) {
751
+ isShared || (isShared = root.isShared);
752
+ this._root = root = root.keys.length === 0 ? EmptyLeaf :
753
+ root.children[0];
754
+ }
755
+ // If any ancestor of the new root was shared, the new root must also be shared
756
+ if (isShared) {
757
+ root.isShared = true;
758
+ }
759
+ }
760
+ };
761
+ /** Same as `editRange` except that the callback is called for all pairs. */
762
+ BTree.prototype.editAll = function (onFound, initialCounter) {
763
+ return this.editRange(this.minKey(), this.maxKey(), true, onFound, initialCounter);
764
+ };
765
+ /**
766
+ * Removes a range of key-value pairs from the B+ tree.
767
+ * @param low The first key scanned will be greater than or equal to `low`.
768
+ * @param high Scanning stops when a key larger than this is reached.
769
+ * @param includeHigh Specifies whether the `high` key, if present, is deleted.
770
+ * @returns The number of key-value pairs that were deleted.
771
+ * @description Computational complexity: O(log size + number of items deleted)
772
+ */
773
+ BTree.prototype.deleteRange = function (low, high, includeHigh) {
774
+ return this.editRange(low, high, includeHigh, DeleteRange);
775
+ };
776
+ /** Deletes a series of keys from the collection. */
777
+ BTree.prototype.deleteKeys = function (keys) {
778
+ for (var i = 0, r = 0; i < keys.length; i++)
779
+ if (this.delete(keys[i]))
780
+ r++;
781
+ return r;
782
+ };
783
+ Object.defineProperty(BTree.prototype, "height", {
784
+ /** Gets the height of the tree: the number of internal nodes between the
785
+ * BTree object and its leaf nodes (zero if there are no internal nodes). */
786
+ get: function () {
787
+ var node = this._root;
788
+ var height = -1;
789
+ while (node) {
790
+ height++;
791
+ node = node.isLeaf ? undefined : node.children[0];
792
+ }
793
+ return height;
794
+ },
795
+ enumerable: false,
796
+ configurable: true
797
+ });
798
+ /** Makes the object read-only to ensure it is not accidentally modified.
799
+ * Freezing does not have to be permanent; unfreeze() reverses the effect.
800
+ * This is accomplished by replacing mutator functions with a function
801
+ * that throws an Error. Compared to using a property (e.g. this.isFrozen)
802
+ * this implementation gives better performance in non-frozen BTrees.
803
+ */
804
+ BTree.prototype.freeze = function () {
805
+ var t = this;
806
+ // Note: all other mutators ultimately call set() or editRange()
807
+ // so we don't need to override those others.
808
+ t.clear = t.set = t.editRange = function () {
809
+ throw new Error("Attempted to modify a frozen BTree");
810
+ };
811
+ };
812
+ /** Ensures mutations are allowed, reversing the effect of freeze(). */
813
+ BTree.prototype.unfreeze = function () {
814
+ // @ts-ignore "The operand of a 'delete' operator must be optional."
815
+ // (wrong: delete does not affect the prototype.)
816
+ delete this.clear;
817
+ // @ts-ignore
818
+ delete this.set;
819
+ // @ts-ignore
820
+ delete this.editRange;
821
+ };
822
+ Object.defineProperty(BTree.prototype, "isFrozen", {
823
+ /** Returns true if the tree appears to be frozen. */
824
+ get: function () {
825
+ return this.hasOwnProperty('editRange');
826
+ },
827
+ enumerable: false,
828
+ configurable: true
829
+ });
830
+ /** Scans the tree for signs of serious bugs (e.g. this.size doesn't match
831
+ * number of elements, internal nodes not caching max element properly...).
832
+ * Computational complexity: O(number of nodes). This method validates cached size
833
+ * information and, optionally, the ordering of keys (including leaves), which
834
+ * takes more time to check (O(size), which is technically the same big-O). */
835
+ BTree.prototype.checkValid = function (checkOrdering) {
836
+ if (checkOrdering === void 0) { checkOrdering = false; }
837
+ var size = this._root.checkValid(0, this, 0, checkOrdering)[0];
838
+ check(size === this.size, "size mismatch: counted ", size, "but stored", this.size);
839
+ };
840
+ return BTree;
841
+ }());
842
+ exports.default = BTree;
843
+ /** A TypeScript helper function that simply returns its argument, typed as
844
+ * `ISortedSet<K>` if the BTree implements it, as it does if `V extends undefined`.
845
+ * If `V` cannot be `undefined`, it returns `unknown` instead. Or at least, that
846
+ * was the intention, but TypeScript is acting weird and may return `ISortedSet<K>`
847
+ * even if `V` can't be `undefined` (discussion: btree-typescript issue #14) */
848
+ function asSet(btree) {
849
+ return btree;
850
+ }
851
+ exports.asSet = asSet;
852
+ if (Symbol && Symbol.iterator) // iterator is equivalent to entries()
853
+ BTree.prototype[Symbol.iterator] = BTree.prototype.entries;
854
+ BTree.prototype.where = BTree.prototype.filter;
855
+ BTree.prototype.setRange = BTree.prototype.setPairs;
856
+ BTree.prototype.add = BTree.prototype.set; // for compatibility with ISetSink<K>
857
+ function iterator(next) {
858
+ if (next === void 0) { next = (function () { return ({ done: true, value: undefined }); }); }
859
+ var result = { next: next };
860
+ if (Symbol && Symbol.iterator)
861
+ result[Symbol.iterator] = function () { return this; };
862
+ return result;
863
+ }
864
+ /** @internal */
865
+ var BNode = /** @class */ (function () {
866
+ function BNode(keys, values) {
867
+ if (keys === void 0) { keys = []; }
868
+ this.keys = keys;
869
+ this.values = values || undefVals;
870
+ this.isShared = undefined;
871
+ }
872
+ Object.defineProperty(BNode.prototype, "isLeaf", {
873
+ get: function () { return this.children === undefined; },
874
+ enumerable: false,
875
+ configurable: true
876
+ });
877
+ BNode.prototype.size = function () {
878
+ return this.keys.length;
879
+ };
880
+ ///////////////////////////////////////////////////////////////////////////
881
+ // Shared methods /////////////////////////////////////////////////////////
882
+ BNode.prototype.maxKey = function () {
883
+ return this.keys[this.keys.length - 1];
884
+ };
885
+ // If key not found, returns i^failXor where i is the insertion index.
886
+ // Callers that don't care whether there was a match will set failXor=0.
887
+ BNode.prototype.indexOf = function (key, failXor, cmp) {
888
+ var keys = this.keys;
889
+ var lo = 0, hi = keys.length, mid = hi >> 1;
890
+ while (lo < hi) {
891
+ var c = cmp(keys[mid], key);
892
+ if (c < 0)
893
+ lo = mid + 1;
894
+ else if (c > 0) // key < keys[mid]
895
+ hi = mid;
896
+ else if (c === 0)
897
+ return mid;
898
+ else {
899
+ // c is NaN or otherwise invalid
900
+ if (key === key) // at least the search key is not NaN
901
+ return keys.length;
902
+ else
903
+ throw new Error("BTree: NaN was used as a key");
904
+ }
905
+ mid = (lo + hi) >> 1;
906
+ }
907
+ return mid ^ failXor;
908
+ // Unrolled version: benchmarks show same speed, not worth using
909
+ /*var i = 1, c: number = 0, sum = 0;
910
+ if (keys.length >= 4) {
911
+ i = 3;
912
+ if (keys.length >= 8) {
913
+ i = 7;
914
+ if (keys.length >= 16) {
915
+ i = 15;
916
+ if (keys.length >= 32) {
917
+ i = 31;
918
+ if (keys.length >= 64) {
919
+ i = 127;
920
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 64 : -64;
921
+ sum += c;
922
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 32 : -32;
923
+ sum += c;
924
+ }
925
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 16 : -16;
926
+ sum += c;
927
+ }
928
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 8 : -8;
929
+ sum += c;
930
+ }
931
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 4 : -4;
932
+ sum += c;
933
+ }
934
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 2 : -2;
935
+ sum += c;
936
+ }
937
+ i += (c = i < keys.length ? cmp(keys[i], key) : 1) < 0 ? 1 : -1;
938
+ c = i < keys.length ? cmp(keys[i], key) : 1;
939
+ sum += c;
940
+ if (c < 0) {
941
+ ++i;
942
+ c = i < keys.length ? cmp(keys[i], key) : 1;
943
+ sum += c;
944
+ }
945
+ if (sum !== sum) {
946
+ if (key === key) // at least the search key is not NaN
947
+ return keys.length ^ failXor;
948
+ else
949
+ throw new Error("BTree: NaN was used as a key");
950
+ }
951
+ return c === 0 ? i : i ^ failXor;*/
952
+ };
953
+ /////////////////////////////////////////////////////////////////////////////
954
+ // Leaf Node: misc //////////////////////////////////////////////////////////
955
+ BNode.prototype.minKey = function () {
956
+ return this.keys[0];
957
+ };
958
+ BNode.prototype.minPair = function (reusedArray) {
959
+ if (this.keys.length === 0)
960
+ return undefined;
961
+ reusedArray[0] = this.keys[0];
962
+ reusedArray[1] = this.values[0];
963
+ return reusedArray;
964
+ };
965
+ BNode.prototype.maxPair = function (reusedArray) {
966
+ if (this.keys.length === 0)
967
+ return undefined;
968
+ var lastIndex = this.keys.length - 1;
969
+ reusedArray[0] = this.keys[lastIndex];
970
+ reusedArray[1] = this.values[lastIndex];
971
+ return reusedArray;
972
+ };
973
+ BNode.prototype.clone = function () {
974
+ var v = this.values;
975
+ return new BNode(this.keys.slice(0), v === undefVals ? v : v.slice(0));
976
+ };
977
+ BNode.prototype.greedyClone = function (force) {
978
+ return this.isShared && !force ? this : this.clone();
979
+ };
980
+ BNode.prototype.get = function (key, defaultValue, tree) {
981
+ var i = this.indexOf(key, -1, tree._compare);
982
+ return i < 0 ? defaultValue : this.values[i];
983
+ };
984
+ BNode.prototype.getPairOrNextLower = function (key, compare, inclusive, reusedArray) {
985
+ var i = this.indexOf(key, -1, compare);
986
+ var indexOrLower = i < 0 ? ~i - 1 : (inclusive ? i : i - 1);
987
+ if (indexOrLower >= 0) {
988
+ reusedArray[0] = this.keys[indexOrLower];
989
+ reusedArray[1] = this.values[indexOrLower];
990
+ return reusedArray;
991
+ }
992
+ return undefined;
993
+ };
994
+ BNode.prototype.getPairOrNextHigher = function (key, compare, inclusive, reusedArray) {
995
+ var i = this.indexOf(key, -1, compare);
996
+ var indexOrLower = i < 0 ? ~i : (inclusive ? i : i + 1);
997
+ var keys = this.keys;
998
+ if (indexOrLower < keys.length) {
999
+ reusedArray[0] = keys[indexOrLower];
1000
+ reusedArray[1] = this.values[indexOrLower];
1001
+ return reusedArray;
1002
+ }
1003
+ return undefined;
1004
+ };
1005
+ BNode.prototype.checkValid = function (depth, tree, baseIndex, checkOrdering) {
1006
+ var kL = this.keys.length, vL = this.values.length;
1007
+ check(this.values === undefVals ? kL <= vL : kL === vL, "keys/values length mismatch: depth", depth, "with lengths", kL, vL, "and baseIndex", baseIndex);
1008
+ // Note: we don't check for "node too small" because sometimes a node
1009
+ // can legitimately have size 1. This occurs if there is a batch
1010
+ // deletion, leaving a node of size 1, and the siblings are full so
1011
+ // it can't be merged with adjacent nodes. However, the parent will
1012
+ // verify that the average node size is at least half of the maximum.
1013
+ check(depth == 0 || kL > 0, "empty leaf at depth", depth, "and baseIndex", baseIndex);
1014
+ if (checkOrdering === true) {
1015
+ for (var i = 1; i < kL; i++) {
1016
+ var c = tree._compare(this.keys[i - 1], this.keys[i]);
1017
+ check(c < 0, "keys out of order at depth", depth, "and baseIndex", baseIndex + i - 1, ": ", this.keys[i - 1], " !< ", this.keys[i]);
1018
+ }
1019
+ }
1020
+ return [kL, this.keys[0], this.keys[kL - 1]];
1021
+ };
1022
+ /////////////////////////////////////////////////////////////////////////////
1023
+ // Leaf Node: set & node splitting //////////////////////////////////////////
1024
+ BNode.prototype.set = function (key, value, overwrite, tree) {
1025
+ var i = this.indexOf(key, -1, tree._compare);
1026
+ if (i < 0) {
1027
+ // key does not exist yet
1028
+ i = ~i;
1029
+ if (this.keys.length < tree._maxNodeSize) {
1030
+ return this.insertInLeaf(i, key, value, tree);
1031
+ }
1032
+ else {
1033
+ // This leaf node is full and must split
1034
+ var newRightSibling = this.splitOffRightSide(), target = this;
1035
+ if (i > this.keys.length) {
1036
+ i -= this.keys.length;
1037
+ target = newRightSibling;
1038
+ }
1039
+ target.insertInLeaf(i, key, value, tree);
1040
+ return newRightSibling;
1041
+ }
1042
+ }
1043
+ else {
1044
+ // Key already exists
1045
+ if (overwrite !== false) {
1046
+ if (value !== undefined)
1047
+ this.reifyValues();
1048
+ // usually this is a no-op, but some users may wish to edit the key
1049
+ this.keys[i] = key;
1050
+ this.values[i] = value;
1051
+ }
1052
+ return false;
1053
+ }
1054
+ };
1055
+ BNode.prototype.reifyValues = function () {
1056
+ if (this.values === undefVals)
1057
+ return this.values = this.values.slice(0, this.keys.length);
1058
+ return this.values;
1059
+ };
1060
+ BNode.prototype.insertInLeaf = function (i, key, value, tree) {
1061
+ this.keys.splice(i, 0, key);
1062
+ if (this.values === undefVals) {
1063
+ while (undefVals.length < tree._maxNodeSize)
1064
+ undefVals.push(undefined);
1065
+ if (value === undefined) {
1066
+ return true;
1067
+ }
1068
+ else {
1069
+ this.values = undefVals.slice(0, this.keys.length - 1);
1070
+ }
1071
+ }
1072
+ this.values.splice(i, 0, value);
1073
+ return true;
1074
+ };
1075
+ BNode.prototype.takeFromRight = function (rhs) {
1076
+ // Reminder: parent node must update its copy of key for this node
1077
+ // assert: neither node is shared
1078
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
1079
+ var v = this.values;
1080
+ if (rhs.values === undefVals) {
1081
+ if (v !== undefVals)
1082
+ v.push(undefined);
1083
+ }
1084
+ else {
1085
+ v = this.reifyValues();
1086
+ v.push(rhs.values.shift());
1087
+ }
1088
+ this.keys.push(rhs.keys.shift());
1089
+ };
1090
+ BNode.prototype.takeFromLeft = function (lhs) {
1091
+ // Reminder: parent node must update its copy of key for this node
1092
+ // assert: neither node is shared
1093
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
1094
+ var v = this.values;
1095
+ if (lhs.values === undefVals) {
1096
+ if (v !== undefVals)
1097
+ v.unshift(undefined);
1098
+ }
1099
+ else {
1100
+ v = this.reifyValues();
1101
+ v.unshift(lhs.values.pop());
1102
+ }
1103
+ this.keys.unshift(lhs.keys.pop());
1104
+ };
1105
+ BNode.prototype.splitOffRightSide = function () {
1106
+ // Reminder: parent node must update its copy of key for this node
1107
+ var half = this.keys.length >> 1, keys = this.keys.splice(half);
1108
+ var values = this.values === undefVals ? undefVals : this.values.splice(half);
1109
+ return new BNode(keys, values);
1110
+ };
1111
+ /////////////////////////////////////////////////////////////////////////////
1112
+ // Leaf Node: scanning & deletions //////////////////////////////////////////
1113
+ BNode.prototype.forRange = function (low, high, includeHigh, editMode, tree, count, onFound) {
1114
+ var cmp = tree._compare;
1115
+ var iLow, iHigh;
1116
+ if (high === low) {
1117
+ if (!includeHigh)
1118
+ return count;
1119
+ iHigh = (iLow = this.indexOf(low, -1, cmp)) + 1;
1120
+ if (iLow < 0)
1121
+ return count;
1122
+ }
1123
+ else {
1124
+ iLow = this.indexOf(low, 0, cmp);
1125
+ iHigh = this.indexOf(high, -1, cmp);
1126
+ if (iHigh < 0)
1127
+ iHigh = ~iHigh;
1128
+ else if (includeHigh === true)
1129
+ iHigh++;
1130
+ }
1131
+ var keys = this.keys, values = this.values;
1132
+ if (onFound !== undefined) {
1133
+ for (var i = iLow; i < iHigh; i++) {
1134
+ var key = keys[i];
1135
+ var result = onFound(key, values[i], count++);
1136
+ if (result !== undefined) {
1137
+ if (editMode === true) {
1138
+ if (key !== keys[i] || this.isShared === true)
1139
+ throw new Error("BTree illegally changed or cloned in editRange");
1140
+ if (result.delete) {
1141
+ this.keys.splice(i, 1);
1142
+ if (this.values !== undefVals)
1143
+ this.values.splice(i, 1);
1144
+ i--;
1145
+ iHigh--;
1146
+ }
1147
+ else if (result.hasOwnProperty('value')) {
1148
+ values[i] = result.value;
1149
+ }
1150
+ }
1151
+ if (result.break !== undefined)
1152
+ return result;
1153
+ }
1154
+ }
1155
+ }
1156
+ else
1157
+ count += iHigh - iLow;
1158
+ return count;
1159
+ };
1160
+ /** Adds entire contents of right-hand sibling (rhs is left unchanged) */
1161
+ BNode.prototype.mergeSibling = function (rhs, _) {
1162
+ this.keys.push.apply(this.keys, rhs.keys);
1163
+ if (this.values === undefVals) {
1164
+ if (rhs.values === undefVals)
1165
+ return;
1166
+ this.values = this.values.slice(0, this.keys.length);
1167
+ }
1168
+ this.values.push.apply(this.values, rhs.reifyValues());
1169
+ };
1170
+ return BNode;
1171
+ }());
1172
+ exports.BNode = BNode;
1173
+ /** Internal node (non-leaf node) ********************************************/
1174
+ /** @internal */
1175
+ var BNodeInternal = /** @class */ (function (_super) {
1176
+ __extends(BNodeInternal, _super);
1177
+ /**
1178
+ * This does not mark `children` as shared, so it is the responsibility of the caller
1179
+ * to ensure children are either marked shared, or aren't included in another tree.
1180
+ */
1181
+ function BNodeInternal(children, size, keys) {
1182
+ var _this = this;
1183
+ if (!keys) {
1184
+ keys = [];
1185
+ for (var i = 0; i < children.length; i++)
1186
+ keys[i] = children[i].maxKey();
1187
+ }
1188
+ _this = _super.call(this, keys) || this;
1189
+ _this.children = children;
1190
+ _this._size = size;
1191
+ return _this;
1192
+ }
1193
+ BNodeInternal.prototype.clone = function () {
1194
+ var children = this.children.slice(0);
1195
+ for (var i = 0; i < children.length; i++)
1196
+ children[i].isShared = true;
1197
+ return new BNodeInternal(children, this._size, this.keys.slice(0));
1198
+ };
1199
+ BNodeInternal.prototype.size = function () {
1200
+ return this._size;
1201
+ };
1202
+ BNodeInternal.prototype.greedyClone = function (force) {
1203
+ if (this.isShared && !force)
1204
+ return this;
1205
+ var nu = new BNodeInternal(this.children.slice(0), this._size, this.keys.slice(0));
1206
+ for (var i = 0; i < nu.children.length; i++)
1207
+ nu.children[i] = nu.children[i].greedyClone(force);
1208
+ return nu;
1209
+ };
1210
+ BNodeInternal.prototype.minKey = function () {
1211
+ return this.children[0].minKey();
1212
+ };
1213
+ BNodeInternal.prototype.minPair = function (reusedArray) {
1214
+ return this.children[0].minPair(reusedArray);
1215
+ };
1216
+ BNodeInternal.prototype.maxPair = function (reusedArray) {
1217
+ return this.children[this.children.length - 1].maxPair(reusedArray);
1218
+ };
1219
+ BNodeInternal.prototype.get = function (key, defaultValue, tree) {
1220
+ var i = this.indexOf(key, 0, tree._compare), children = this.children;
1221
+ return i < children.length ? children[i].get(key, defaultValue, tree) : undefined;
1222
+ };
1223
+ BNodeInternal.prototype.getPairOrNextLower = function (key, compare, inclusive, reusedArray) {
1224
+ var i = this.indexOf(key, 0, compare), children = this.children;
1225
+ if (i >= children.length)
1226
+ return this.maxPair(reusedArray);
1227
+ var result = children[i].getPairOrNextLower(key, compare, inclusive, reusedArray);
1228
+ if (result === undefined && i > 0) {
1229
+ return children[i - 1].maxPair(reusedArray);
1230
+ }
1231
+ return result;
1232
+ };
1233
+ BNodeInternal.prototype.getPairOrNextHigher = function (key, compare, inclusive, reusedArray) {
1234
+ var i = this.indexOf(key, 0, compare), children = this.children, length = children.length;
1235
+ if (i >= length)
1236
+ return undefined;
1237
+ var result = children[i].getPairOrNextHigher(key, compare, inclusive, reusedArray);
1238
+ if (result === undefined && i < length - 1) {
1239
+ return children[i + 1].minPair(reusedArray);
1240
+ }
1241
+ return result;
1242
+ };
1243
+ BNodeInternal.prototype.checkValid = function (depth, tree, baseIndex, checkOrdering) {
1244
+ var kL = this.keys.length, cL = this.children.length;
1245
+ check(kL === cL, "keys/children length mismatch: depth", depth, "lengths", kL, cL, "baseIndex", baseIndex);
1246
+ check(kL > 1 || depth > 0, "internal node has length", kL, "at depth", depth, "baseIndex", baseIndex);
1247
+ var size = 0, c = this.children, k = this.keys, childSize = 0;
1248
+ var prevMinKey = undefined;
1249
+ var prevMaxKey = undefined;
1250
+ for (var i = 0; i < cL; i++) {
1251
+ var child = c[i];
1252
+ var _a = child.checkValid(depth + 1, tree, baseIndex + size, checkOrdering), subtreeSize = _a[0], minKey = _a[1], maxKey = _a[2];
1253
+ check(subtreeSize === child.size(), "cached size mismatch at depth", depth, "index", i, "baseIndex", baseIndex);
1254
+ check(subtreeSize === 1 || tree._compare(minKey, maxKey) < 0, "child node keys not sorted at depth", depth, "index", i, "baseIndex", baseIndex);
1255
+ if (prevMinKey !== undefined && prevMaxKey !== undefined && checkOrdering) {
1256
+ check(!areOverlapping(prevMinKey, prevMaxKey, minKey, maxKey, tree._compare), "children keys not sorted at depth", depth, "index", i, "baseIndex", baseIndex, ": ", prevMaxKey, " !< ", minKey);
1257
+ check(tree._compare(prevMaxKey, minKey) < 0, "children keys not sorted at depth", depth, "index", i, "baseIndex", baseIndex, ": ", prevMaxKey, " !< ", minKey);
1258
+ }
1259
+ prevMinKey = minKey;
1260
+ prevMaxKey = maxKey;
1261
+ size += subtreeSize;
1262
+ childSize += child.keys.length;
1263
+ check(size >= childSize, "wtf", baseIndex); // no way this will ever fail
1264
+ check(i === 0 || c[i - 1].constructor === child.constructor, "type mismatch, baseIndex:", baseIndex);
1265
+ if (child.maxKey() != k[i])
1266
+ check(false, "keys[", i, "] =", k[i], "is wrong, should be ", child.maxKey(), "at depth", depth, "baseIndex", baseIndex);
1267
+ if (!(i === 0 || tree._compare(k[i - 1], k[i]) < 0))
1268
+ check(false, "sort violation at depth", depth, "index", i, "keys", k[i - 1], k[i]);
1269
+ }
1270
+ check(this._size === size, "internal node cached size mismatch at depth", depth, "baseIndex", baseIndex, "cached", this._size, "actual", size);
1271
+ // 2020/08: BTree doesn't always avoid grossly undersized nodes,
1272
+ // but AFAIK such nodes are pretty harmless, so accept them.
1273
+ var toofew = childSize === 0; // childSize < (tree.maxNodeSize >> 1)*cL;
1274
+ if (toofew || childSize > tree.maxNodeSize * cL)
1275
+ check(false, toofew ? "too few" : "too many", "children (", childSize, size, ") at depth", depth, "maxNodeSize:", tree.maxNodeSize, "children.length:", cL, "baseIndex:", baseIndex);
1276
+ return [size, this.minKey(), this.maxKey()];
1277
+ };
1278
+ /////////////////////////////////////////////////////////////////////////////
1279
+ // Internal Node: set & node splitting //////////////////////////////////////
1280
+ BNodeInternal.prototype.set = function (key, value, overwrite, tree) {
1281
+ var c = this.children, max = tree._maxNodeSize, cmp = tree._compare;
1282
+ var i = Math.min(this.indexOf(key, 0, cmp), c.length - 1), child = c[i];
1283
+ if (child.isShared)
1284
+ c[i] = child = child.clone();
1285
+ if (child.keys.length >= max) {
1286
+ // child is full; inserting anything else will cause a split.
1287
+ // Shifting an item to the left or right sibling may avoid a split.
1288
+ // We can do a shift if the adjacent node is not full and if the
1289
+ // current key can still be placed in the same node after the shift.
1290
+ var other;
1291
+ if (i > 0 && (other = c[i - 1]).keys.length < max && cmp(child.keys[0], key) < 0) {
1292
+ if (other.isShared)
1293
+ c[i - 1] = other = other.clone();
1294
+ other.takeFromRight(child);
1295
+ this.keys[i - 1] = other.maxKey();
1296
+ }
1297
+ else if ((other = c[i + 1]) !== undefined && other.keys.length < max && cmp(child.maxKey(), key) < 0) {
1298
+ if (other.isShared)
1299
+ c[i + 1] = other = other.clone();
1300
+ other.takeFromLeft(child);
1301
+ this.keys[i] = c[i].maxKey();
1302
+ }
1303
+ }
1304
+ var oldSize = child.size();
1305
+ var result = child.set(key, value, overwrite, tree);
1306
+ this._size += child.size() - oldSize;
1307
+ if (result === false)
1308
+ return false;
1309
+ this.keys[i] = child.maxKey();
1310
+ if (result === true)
1311
+ return true;
1312
+ // The child has split and `result` is a new right child... does it fit?
1313
+ if (this.keys.length < max) { // yes
1314
+ this.insert(i + 1, result);
1315
+ return true;
1316
+ }
1317
+ else { // no, we must split also
1318
+ var newRightSibling = this.splitOffRightSide(), target = this;
1319
+ if (cmp(result.maxKey(), this.maxKey()) > 0) {
1320
+ target = newRightSibling;
1321
+ i -= this.keys.length;
1322
+ }
1323
+ target.insert(i + 1, result);
1324
+ return newRightSibling;
1325
+ }
1326
+ };
1327
+ /**
1328
+ * Inserts `child` at index `i`.
1329
+ * This does not mark `child` as shared, so it is the responsibility of the caller
1330
+ * to ensure that either child is marked shared, or it is not included in another tree.
1331
+ */
1332
+ BNodeInternal.prototype.insert = function (i, child) {
1333
+ this.children.splice(i, 0, child);
1334
+ this.keys.splice(i, 0, child.maxKey());
1335
+ this._size += child.size();
1336
+ };
1337
+ /**
1338
+ * Split this node.
1339
+ * Modifies this to remove the second half of the items, returning a separate node containing them.
1340
+ */
1341
+ BNodeInternal.prototype.splitOffRightSide = function () {
1342
+ // assert !this.isShared;
1343
+ var half = this.children.length >> 1;
1344
+ var newChildren = this.children.splice(half);
1345
+ var newKeys = this.keys.splice(half);
1346
+ var sizePrev = this._size;
1347
+ this._size = sumChildSizes(this.children);
1348
+ var newNode = new BNodeInternal(newChildren, sizePrev - this._size, newKeys);
1349
+ return newNode;
1350
+ };
1351
+ /**
1352
+ * Split this node.
1353
+ * Modifies this to remove the first half of the items, returning a separate node containing them.
1354
+ */
1355
+ BNodeInternal.prototype.splitOffLeftSide = function () {
1356
+ // assert !this.isShared;
1357
+ var half = this.children.length >> 1;
1358
+ var newChildren = this.children.splice(0, half);
1359
+ var newKeys = this.keys.splice(0, half);
1360
+ var sizePrev = this._size;
1361
+ this._size = sumChildSizes(this.children);
1362
+ var newNode = new BNodeInternal(newChildren, sizePrev - this._size, newKeys);
1363
+ return newNode;
1364
+ };
1365
+ BNodeInternal.prototype.takeFromRight = function (rhs) {
1366
+ // Reminder: parent node must update its copy of key for this node
1367
+ // assert: neither node is shared
1368
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
1369
+ var rhsInternal = rhs;
1370
+ this.keys.push(rhs.keys.shift());
1371
+ var child = rhsInternal.children.shift();
1372
+ this.children.push(child);
1373
+ var size = child.size();
1374
+ rhsInternal._size -= size;
1375
+ this._size += size;
1376
+ };
1377
+ BNodeInternal.prototype.takeFromLeft = function (lhs) {
1378
+ // Reminder: parent node must update its copy of key for this node
1379
+ // assert: neither node is shared
1380
+ // assert rhs.keys.length > (maxNodeSize/2 && this.keys.length<maxNodeSize)
1381
+ var lhsInternal = lhs;
1382
+ var child = lhsInternal.children.pop();
1383
+ this.keys.unshift(lhs.keys.pop());
1384
+ this.children.unshift(child);
1385
+ var size = child.size();
1386
+ lhsInternal._size -= size;
1387
+ this._size += size;
1388
+ };
1389
+ /////////////////////////////////////////////////////////////////////////////
1390
+ // Internal Node: scanning & deletions //////////////////////////////////////
1391
+ // Note: `count` is the next value of the third argument to `onFound`.
1392
+ // A leaf node's `forRange` function returns a new value for this counter,
1393
+ // unless the operation is to stop early.
1394
+ BNodeInternal.prototype.forRange = function (low, high, includeHigh, editMode, tree, count, onFound) {
1395
+ var cmp = tree._compare;
1396
+ var keys = this.keys, children = this.children;
1397
+ var iLow = this.indexOf(low, 0, cmp), i = iLow;
1398
+ var iHigh = Math.min(high === low ? iLow : this.indexOf(high, 0, cmp), keys.length - 1);
1399
+ if (!editMode) {
1400
+ // Simple case
1401
+ for (; i <= iHigh; i++) {
1402
+ var result = children[i].forRange(low, high, includeHigh, editMode, tree, count, onFound);
1403
+ if (typeof result !== 'number')
1404
+ return result;
1405
+ count = result;
1406
+ }
1407
+ }
1408
+ else if (i <= iHigh) {
1409
+ try {
1410
+ for (; i <= iHigh; i++) {
1411
+ var child = children[i];
1412
+ if (child.isShared)
1413
+ children[i] = child = child.clone();
1414
+ var beforeSize = child.size();
1415
+ var result_1 = child.forRange(low, high, includeHigh, editMode, tree, count, onFound);
1416
+ // Note: if children[i] is empty then keys[i]=undefined.
1417
+ // This is an invalid state, but it is fixed below.
1418
+ keys[i] = child.maxKey();
1419
+ this._size += child.size() - beforeSize;
1420
+ if (typeof result_1 !== 'number')
1421
+ return result_1;
1422
+ count = result_1;
1423
+ }
1424
+ }
1425
+ finally {
1426
+ // Deletions may have occurred, so look for opportunities to merge nodes.
1427
+ var half = tree._maxNodeSize >> 1;
1428
+ if (iLow > 0)
1429
+ iLow--;
1430
+ for (i = iHigh; i >= iLow; i--) {
1431
+ if (children[i].keys.length <= half) {
1432
+ if (children[i].keys.length !== 0) {
1433
+ this.tryMerge(i, tree._maxNodeSize);
1434
+ }
1435
+ else { // child is empty! delete it!
1436
+ keys.splice(i, 1);
1437
+ var removed = children.splice(i, 1);
1438
+ check(removed[0].size() === 0, "emptiness cleanup");
1439
+ }
1440
+ }
1441
+ }
1442
+ if (children.length !== 0 && children[0].keys.length === 0)
1443
+ check(false, "emptiness bug");
1444
+ }
1445
+ }
1446
+ return count;
1447
+ };
1448
+ /** Merges child i with child i+1 if their combined size is not too large */
1449
+ BNodeInternal.prototype.tryMerge = function (i, maxSize) {
1450
+ var children = this.children;
1451
+ if (i >= 0 && i + 1 < children.length) {
1452
+ if (children[i].keys.length + children[i + 1].keys.length <= maxSize) {
1453
+ if (children[i].isShared) // cloned already UNLESS i is outside scan range
1454
+ children[i] = children[i].clone();
1455
+ children[i].mergeSibling(children[i + 1], maxSize);
1456
+ children.splice(i + 1, 1);
1457
+ this.keys.splice(i + 1, 1);
1458
+ this.keys[i] = children[i].maxKey();
1459
+ return true;
1460
+ }
1461
+ }
1462
+ return false;
1463
+ };
1464
+ /**
1465
+ * Move children from `rhs` into this.
1466
+ * `rhs` must be part of this tree, and be removed from it after this call
1467
+ * (otherwise isShared for its children could be incorrect).
1468
+ */
1469
+ BNodeInternal.prototype.mergeSibling = function (rhs, maxNodeSize) {
1470
+ // assert !this.isShared;
1471
+ var oldLength = this.keys.length;
1472
+ this.keys.push.apply(this.keys, rhs.keys);
1473
+ var rhsChildren = rhs.children;
1474
+ this.children.push.apply(this.children, rhsChildren);
1475
+ this._size += rhs.size();
1476
+ if (rhs.isShared && !this.isShared) {
1477
+ // All children of a shared node are implicitly shared, and since their new
1478
+ // parent is not shared, they must now be explicitly marked as shared.
1479
+ for (var i = 0; i < rhsChildren.length; i++)
1480
+ rhsChildren[i].isShared = true;
1481
+ }
1482
+ // If our children are themselves almost empty due to a mass-delete,
1483
+ // they may need to be merged too (but only the oldLength-1 and its
1484
+ // right sibling should need this).
1485
+ this.tryMerge(oldLength - 1, maxNodeSize);
1486
+ };
1487
+ return BNodeInternal;
1488
+ }(BNode));
1489
+ exports.BNodeInternal = BNodeInternal;
1490
+ // Optimization: this array of `undefined`s is used instead of a normal
1491
+ // array of values in nodes where `undefined` is the only value.
1492
+ // Its length is extended to max node size on first use; since it can
1493
+ // be shared between trees with different maximums, its length can only
1494
+ // increase, never decrease. Its type should be undefined[] but strangely
1495
+ // TypeScript won't allow the comparison V[] === undefined[]. To prevent
1496
+ // users from making this array too large, BTree has a maximum node size.
1497
+ //
1498
+ // FAQ: undefVals[i] is already undefined, so why increase the array size?
1499
+ // Reading outside the bounds of an array is relatively slow because it
1500
+ // has the side effect of scanning the prototype chain.
1501
+ var undefVals = [];
1502
+ /**
1503
+ * Sums the sizes of the given child nodes.
1504
+ * @param children the child nodes
1505
+ * @returns the total size
1506
+ * @internal
1507
+ */
1508
+ function sumChildSizes(children) {
1509
+ var total = 0;
1510
+ for (var i = 0; i < children.length; i++)
1511
+ total += children[i].size();
1512
+ return total;
1513
+ }
1514
+ exports.sumChildSizes = sumChildSizes;
1515
+ /**
1516
+ * Determines whether two nodes are overlapping in key range.
1517
+ * @internal
1518
+ */
1519
+ function areOverlapping(aMin, aMax, bMin, bMax, cmp) {
1520
+ return cmp(aMin, bMax) <= 0 && cmp(aMax, bMin) >= 0;
1521
+ }
1522
+ exports.areOverlapping = areOverlapping;
1523
+ var Delete = { delete: true }, DeleteRange = function () { return Delete; };
1524
+ var Break = { break: true };
1525
+ var EmptyLeaf = (function () {
1526
+ var n = new BNode();
1527
+ n.isShared = true;
1528
+ return n;
1529
+ })();
1530
+ var EmptyArray = [];
1531
+ var ReusedArray = []; // assumed thread-local
1532
+ /** @internal */
1533
+ function check(fact) {
1534
+ var args = [];
1535
+ for (var _i = 1; _i < arguments.length; _i++) {
1536
+ args[_i - 1] = arguments[_i];
1537
+ }
1538
+ if (!fact) {
1539
+ args.unshift('B+ tree'); // at beginning of message
1540
+ throw new Error(args.join(' '));
1541
+ }
1542
+ }
1543
+ exports.check = check;
1544
+ /** A BTree frozen in the empty state. */
1545
+ exports.EmptyBTree = (function () { var t = new BTree(); t.freeze(); return t; })();