@mark1russell7/collections 0.9.1 → 0.9.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.
@@ -1,15 +1,9 @@
1
1
  /**
2
- * SummaryTree: a persistent sequence of leaves with a summary of each part.
2
+ * SummaryTree: the class form of the summary tree, a persistent sequence of leaves with a summary of each part.
3
3
  *
4
- * The tree is a balanced binary tree (AVL) with one leaf in each node. Each node keeps the summary of its subtree.
5
- * A summary is a value of a monoid: the caller gives the monoid as data, with `empty` and `combine`. The order of the
6
- * leaves is kept, so `combine` must be associative, but it can be non-commutative.
7
- *
8
- * Each operation gives a new tree and keeps the old tree. The two trees share the nodes that did not change.
9
- * Concatenation, a split at an index or at a summary search, an edit and a lookup are O(log n).
10
- *
11
- * The algorithms are the "join" algorithms of Blelloch, Ferizovic and Sun, "Just Join for Parallel Ordered Sets"
12
- * (SPAA 2016).
4
+ * The class wraps the plain functions of the entry `@mark1russell7/collections/summary-tree`. Its `record` is the
5
+ * plain record that those functions take. A bundle that uses the class keeps each of its methods, so a program that
6
+ * calls only a few operations imports the functions instead.
13
7
  *
14
8
  * @example
15
9
  * // The number of leaves and the total length of the strings
@@ -22,359 +16,59 @@
22
16
  * const [left, right] = tree.split((prefix) => prefix.length > 2); // left: ["ab"], right: ["cde", "f"]
23
17
  */
24
18
 
25
- /** A monoid as data: the identity value `empty` and an associative operation `combine`. */
26
- export interface SummaryMonoid<Summary> {
27
- /** The summary of a sequence with no leaf. `combine(empty, s)` and `combine(s, empty)` are equal to `s`. */
28
- readonly empty: Summary;
29
- /** This function gives the summary of a sequence from the summaries of its two parts, left first. */
30
- readonly combine: (left: Summary, right: Summary) => Summary;
31
- }
32
-
33
- /** The data that a tree needs: the monoid of the summaries and the summary of one leaf. */
34
- export interface SummarySpec<Leaf, Summary> {
35
- readonly monoid: SummaryMonoid<Summary>;
36
- /** This function gives the summary of one leaf. */
37
- readonly measure: (leaf: Leaf) => Summary;
38
- /**
39
- * This optional function joins two neighbor leaves at a seam into one leaf, or gives `undefined` to keep both. A seam
40
- * is the place where `concat`, `append`, `prepend`, `splice`, `insert` or `remove` puts two leaves next to each other.
41
- * The tree calls it once at each seam, and not between the leaves that one call inserts. `set` does not call it.
42
- */
43
- readonly merge?: (left: Leaf, right: Leaf) => Leaf | undefined;
44
- }
45
-
46
- /** The result of a summary search: the first leaf whose prefix summary satisfies the predicate. */
47
- export interface SummarySearch<Leaf, Summary> {
48
- /** The index of the leaf. */
49
- readonly index: number;
50
- readonly leaf: Leaf;
51
- /** The summary of the leaves before the leaf. */
52
- readonly before: Summary;
53
- /** The summary of the leaves before the leaf, and of the leaf. */
54
- readonly through: Summary;
55
- }
56
-
57
- /** The result of `locate`: the leaf that holds a position of an additive key, and the position in that leaf. */
58
- export interface SummaryLocation<Leaf> {
59
- /** The index of the leaf. */
60
- readonly index: number;
61
- readonly leaf: Leaf;
62
- /** The position in the leaf: the target minus the key of the leaves before the leaf. */
63
- readonly offset: number;
64
- }
65
-
66
- /** One node of the tree. The tree does not change a node after it makes it. */
67
- interface Node<Leaf, Summary> {
68
- readonly left: Node<Leaf, Summary> | null;
69
- readonly leaf: Leaf;
70
- /** The summary of the leaf of this node only. */
71
- readonly own: Summary;
72
- /** The summary of the leaves of the left subtree and the leaf of this node. A copy with the same left subtree and leaf keeps it. */
73
- readonly inner: Summary;
74
- readonly right: Node<Leaf, Summary> | null;
75
- readonly height: number;
76
- readonly size: number;
77
- /** The summary of all the leaves of this subtree. */
78
- readonly summary: Summary;
79
- }
80
-
81
- type Tree<Leaf, Summary> = Node<Leaf, Summary> | null;
82
-
83
- function heightOf<L, S>(tree: Tree<L, S>): number {
84
- return tree === null ? 0 : tree.height;
85
- }
86
-
87
- function sizeOf<L, S>(tree: Tree<L, S>): number {
88
- return tree === null ? 0 : tree.size;
89
- }
19
+ import * as Tree from "../summary-tree/functions.js";
20
+ import type { SummaryLocation, SummaryNode, SummarySearch, SummarySpec, SummaryTreeRecord } from "../summary-tree/functions.js";
90
21
 
91
- /** The functions that make and join nodes for one monoid. */
92
- class Builder<L, S> {
93
- readonly spec: SummarySpec<L, S>;
94
-
95
- constructor(spec: SummarySpec<L, S>) {
96
- this.spec = spec;
97
- }
98
-
99
- summaryOf(tree: Tree<L, S>): S {
100
- return tree === null ? this.spec.monoid.empty : tree.summary;
101
- }
102
-
103
- /** This function makes a node. Give `inner` only when it is the summary of `left` and `own`, to save one `combine`. */
104
- node(left: Tree<L, S>, leaf: L, own: S, right: Tree<L, S>, inner?: S): Node<L, S> {
105
- if (inner === undefined) inner = left === null ? own : this.spec.monoid.combine(left.summary, own);
106
- return {
107
- left,
108
- leaf,
109
- own,
110
- inner,
111
- right,
112
- height: 1 + Math.max(heightOf(left), heightOf(right)),
113
- size: sizeOf(left) + 1 + sizeOf(right),
114
- summary: right === null ? inner : this.spec.monoid.combine(inner, right.summary),
115
- };
116
- }
117
-
118
- /** This function copies a node with a new right subtree. It keeps the summary `inner`, so it calls `combine` once at most. */
119
- withRight(n: Node<L, S>, right: Tree<L, S>): Node<L, S> {
120
- return this.node(n.left, n.leaf, n.own, right, n.inner);
121
- }
122
-
123
- rotateLeft(n: Node<L, S>): Node<L, S> {
124
- const r = n.right!;
125
- return this.node(this.withRight(n, r.left), r.leaf, r.own, r.right);
126
- }
127
-
128
- rotateRight(n: Node<L, S>): Node<L, S> {
129
- const l = n.left!;
130
- return this.withRight(l, this.node(l.right, n.leaf, n.own, n.right));
131
- }
132
-
133
- /** This function joins a tree that is higher by more than 1 with a leaf and a lower tree on its right. */
134
- joinRight(left: Node<L, S>, leaf: L, own: S, right: Tree<L, S>): Node<L, S> {
135
- const c = left.right;
136
- if (heightOf(c) <= heightOf(right) + 1) {
137
- const t = this.node(c, leaf, own, right);
138
- if (t.height <= heightOf(left.left) + 1) return this.withRight(left, t);
139
- return this.rotateLeft(this.withRight(left, this.rotateRight(t)));
140
- }
141
- const t = this.joinRight(c!, leaf, own, right);
142
- const joined = this.withRight(left, t);
143
- return t.height <= heightOf(left.left) + 1 ? joined : this.rotateLeft(joined);
144
- }
145
-
146
- /** This function joins a lower tree on the left with a leaf and a tree that is higher by more than 1. */
147
- joinLeft(left: Tree<L, S>, leaf: L, own: S, right: Node<L, S>, inner?: S): Node<L, S> {
148
- const c = right.left;
149
- if (heightOf(c) <= heightOf(left) + 1) {
150
- const t = this.node(left, leaf, own, c, inner);
151
- if (t.height <= heightOf(right.right) + 1) return this.node(t, right.leaf, right.own, right.right);
152
- return this.rotateRight(this.node(this.rotateLeft(t), right.leaf, right.own, right.right));
153
- }
154
- const t = this.joinLeft(left, leaf, own, c!, inner);
155
- const joined = this.node(t, right.leaf, right.own, right.right);
156
- return t.height <= heightOf(right.right) + 1 ? joined : this.rotateRight(joined);
157
- }
158
-
159
- /**
160
- * This function gives the tree of the leaves of `left`, then `leaf`, then the leaves of `right`. Give `inner` only
161
- * when it is the summary of `left` and `own`.
162
- */
163
- join(left: Tree<L, S>, leaf: L, own: S, right: Tree<L, S>, inner?: S): Node<L, S> {
164
- if (heightOf(left) > heightOf(right) + 1) return this.joinRight(left!, leaf, own, right);
165
- if (heightOf(right) > heightOf(left) + 1) return this.joinLeft(left, leaf, own, right!, inner);
166
- return this.node(left, leaf, own, right, inner);
167
- }
168
-
169
- /** This function removes the last leaf of a tree, and gives the rest and the node of that leaf. */
170
- splitLast(tree: Node<L, S>): [Tree<L, S>, Node<L, S>] {
171
- if (tree.right === null) return [tree.left, tree];
172
- const [rest, last] = this.splitLast(tree.right);
173
- return [this.join(tree.left, tree.leaf, tree.own, rest, tree.inner), last];
174
- }
175
-
176
- concat(left: Tree<L, S>, right: Tree<L, S>): Tree<L, S> {
177
- if (left === null) return right;
178
- if (right === null) return left;
179
- const [rest, last] = this.splitLast(left);
180
- return this.join(rest, last.leaf, last.own, right);
181
- }
182
-
183
- /** This function splits a tree into its first `index` leaves and the other leaves. */
184
- splitAt(tree: Tree<L, S>, index: number): [Tree<L, S>, Tree<L, S>] {
185
- if (tree === null) return [null, null];
186
- const before = sizeOf(tree.left);
187
- if (index <= before) {
188
- const [a, b] = this.splitAt(tree.left, index);
189
- return [a, this.join(b, tree.leaf, tree.own, tree.right)];
190
- }
191
- const [a, b] = this.splitAt(tree.right, index - before - 1);
192
- return [this.join(tree.left, tree.leaf, tree.own, a, tree.inner), b];
193
- }
194
-
195
- /** This function splits a tree before the first leaf whose prefix summary, after `acc`, satisfies the predicate. */
196
- splitBy(tree: Tree<L, S>, predicate: (prefix: S) => boolean, acc: S): [Tree<L, S>, Tree<L, S>] {
197
- if (tree === null) return [null, null];
198
- const { combine } = this.spec.monoid;
199
- const throughLeft = tree.left === null ? acc : combine(acc, tree.left.summary);
200
- if (tree.left !== null && predicate(throughLeft)) {
201
- const [a, b] = this.splitBy(tree.left, predicate, acc);
202
- return [a, this.join(b, tree.leaf, tree.own, tree.right)];
203
- }
204
- const throughLeaf = combine(throughLeft, tree.own);
205
- if (predicate(throughLeaf)) return [tree.left, this.join(null, tree.leaf, tree.own, tree.right)];
206
- const [a, b] = this.splitBy(tree.right, predicate, throughLeaf);
207
- return [this.join(tree.left, tree.leaf, tree.own, a, tree.inner), b];
208
- }
209
-
210
- /** This function replaces the leaf at an index in the tree. It copies only the path to the leaf. */
211
- replaceAt(tree: Node<L, S>, index: number, leaf: L, own: S): Node<L, S> {
212
- const before = sizeOf(tree.left);
213
- if (index === before) return this.node(tree.left, leaf, own, tree.right);
214
- if (index < before) return this.node(this.replaceAt(tree.left!, index, leaf, own), tree.leaf, tree.own, tree.right);
215
- return this.withRight(tree, this.replaceAt(tree.right!, index - before - 1, leaf, own));
216
- }
217
-
218
- /** This function puts one leaf before the leaf at an index. It copies only the path, and `join` keeps the balance. */
219
- insertAt(tree: Tree<L, S>, index: number, leaf: L, own: S): Node<L, S> {
220
- if (tree === null) return this.node(null, leaf, own, null);
221
- const before = sizeOf(tree.left);
222
- if (index <= before) return this.join(this.insertAt(tree.left, index, leaf, own), tree.leaf, tree.own, tree.right);
223
- return this.join(tree.left, tree.leaf, tree.own, this.insertAt(tree.right, index - before - 1, leaf, own), tree.inner);
224
- }
225
-
226
- /**
227
- * This function replaces the leaf at an index with one or more leaves. It descends once.
228
- * At the node of the leaf, it puts the first new leaf in the node.
229
- * It puts the other new leaves at the start of the right subtree of that node.
230
- */
231
- replaceSpan(tree: Node<L, S>, index: number, leaves: readonly L[]): Node<L, S> {
232
- const before = sizeOf(tree.left);
233
- if (index < before) return this.join(this.replaceSpan(tree.left!, index, leaves), tree.leaf, tree.own, tree.right);
234
- if (index > before) return this.join(tree.left, tree.leaf, tree.own, this.replaceSpan(tree.right!, index - before - 1, leaves), tree.inner);
235
- let right = tree.right;
236
- for (let i = 1; i < leaves.length; i++) right = this.insertAt(right, i - 1, leaves[i]!, this.spec.measure(leaves[i]!));
237
- return this.join(tree.left, leaves[0]!, this.spec.measure(leaves[0]!), right);
238
- }
239
-
240
- /** This function removes the leaf at an index. It copies only the path, and `join` keeps the balance. */
241
- removeAt(tree: Node<L, S>, index: number): Tree<L, S> {
242
- const before = sizeOf(tree.left);
243
- if (index === before) return this.concat(tree.left, tree.right);
244
- if (index < before) return this.join(this.removeAt(tree.left!, index), tree.leaf, tree.own, tree.right);
245
- return this.join(tree.left, tree.leaf, tree.own, this.removeAt(tree.right!, index - before - 1), tree.inner);
246
- }
247
-
248
- /** This function gives the leaf at an index of the tree. The index must be in the tree. */
249
- leafAt(tree: Node<L, S>, index: number): L {
250
- let node = tree;
251
- for (;;) {
252
- const before = sizeOf(node.left);
253
- if (index === before) return node.leaf;
254
- if (index < before) node = node.left!;
255
- else {
256
- index -= before + 1;
257
- node = node.right!;
258
- }
259
- }
260
- }
261
-
262
- /** This function joins the leaves at `index` and `index + 1` when `spec.merge` gives one leaf for them. */
263
- seam(tree: Tree<L, S>, index: number): Tree<L, S> {
264
- const { merge } = this.spec;
265
- if (merge === undefined || tree === null || index < 0 || index + 1 >= tree.size) return tree;
266
- const merged = merge(this.leafAt(tree, index), this.leafAt(tree, index + 1));
267
- if (merged === undefined) return tree;
268
- return this.removeAt(this.replaceAt(tree, index, merged, this.spec.measure(merged)), index + 1);
269
- }
270
-
271
- /** This function makes a balanced tree of the leaves `items[lo]` to `items[hi - 1]`. */
272
- build(items: readonly L[], lo: number, hi: number): Tree<L, S> {
273
- if (lo >= hi) return null;
274
- const mid = (lo + hi) >>> 1;
275
- const leaf = items[mid]!;
276
- return this.node(this.build(items, lo, mid), leaf, this.spec.measure(leaf), this.build(items, mid + 1, hi));
277
- }
278
- }
279
-
280
- /** The largest number of removed and inserted leaves for which `splice` copies paths instead of splitting the tree. */
281
- const SMALL_EDIT = 8;
282
-
283
- /** The builders of each spec. Each spec has one builder, so that two trees of the same spec can be joined. */
284
- const builders = new WeakMap<object, Builder<unknown, unknown>>();
285
-
286
- function builderOf<L, S>(spec: SummarySpec<L, S>): Builder<L, S> {
287
- let builder = builders.get(spec) as Builder<L, S> | undefined;
288
- if (builder === undefined) {
289
- builder = new Builder(spec);
290
- builders.set(spec, builder as Builder<unknown, unknown>);
291
- }
292
- return builder;
293
- }
294
-
295
- function* walk<L, S>(tree: Tree<L, S>): Generator<L, void, undefined> {
296
- // An explicit stack: the depth of the tree is O(log n), so the stack stays small
297
- const stack: Node<L, S>[] = [];
298
- let node = tree;
299
- while (node !== null || stack.length > 0) {
300
- while (node !== null) {
301
- stack.push(node);
302
- node = node.left;
303
- }
304
- const top = stack.pop()!;
305
- yield top.leaf;
306
- node = top.right;
307
- }
308
- }
309
-
310
- /** This function gives the index of a leaf, with a negative index counted from the end, or -1 when it is not in the tree. */
311
- function indexOf(index: number, size: number): number {
312
- if (!Number.isInteger(index)) return -1;
313
- const at = index < 0 ? size + index : index;
314
- return at >= 0 && at < size ? at : -1;
315
- }
316
-
317
- function clamp(value: number, size: number): number {
318
- if (Number.isNaN(value)) return 0;
319
- const whole = Math.trunc(value);
320
- return whole < 0 ? Math.max(0, size + whole) : Math.min(whole, size);
321
- }
22
+ export type { SummaryLocation, SummaryMonoid, SummaryNode, SummarySearch, SummarySpec, SummaryTreeRecord } from "../summary-tree/functions.js";
322
23
 
323
24
  /**
324
25
  * A persistent sequence of leaves with a summary of each part. Make one with `summaryTree`. Each method that changes
325
26
  * the sequence gives a new tree.
326
27
  */
327
28
  export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
328
- private readonly builder: Builder<Leaf, Summary>;
329
- private readonly root: Tree<Leaf, Summary>;
29
+ /** The plain record of the tree: its spec and its root. The functions of the entry `./summary-tree` take it. */
30
+ readonly record: SummaryTreeRecord<Leaf, Summary>;
330
31
 
331
- private constructor(builder: Builder<Leaf, Summary>, root: Tree<Leaf, Summary>) {
332
- this.builder = builder;
333
- this.root = root;
32
+ private constructor(record: SummaryTreeRecord<Leaf, Summary>) {
33
+ this.record = record;
334
34
  }
335
35
 
336
36
  /** This function makes a tree of a spec from leaves, as `summaryTree` does. */
337
37
  static of<Leaf, Summary>(spec: SummarySpec<Leaf, Summary>, leaves: Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {
338
- const builder = builderOf(spec);
339
- const items = [...leaves];
340
- return new SummaryTree(builder, builder.build(items, 0, items.length));
38
+ return new SummaryTree(Tree.of(spec, leaves));
341
39
  }
342
40
 
343
- private wrap(root: Tree<Leaf, Summary>): SummaryTree<Leaf, Summary> {
344
- return root === this.root ? this : new SummaryTree(this.builder, root);
41
+ /** This function wraps a plain record of the entry `./summary-tree` in a tree. It does not copy the nodes. */
42
+ static fromRecord<Leaf, Summary>(record: SummaryTreeRecord<Leaf, Summary>): SummaryTree<Leaf, Summary> {
43
+ return new SummaryTree(record);
345
44
  }
346
45
 
347
- private treeOf(leaves: Iterable<Leaf> | SummaryTree<Leaf, Summary>): Tree<Leaf, Summary> {
348
- if (leaves instanceof SummaryTree) {
349
- if (leaves.builder !== this.builder) throw new TypeError("SummaryTree: the two trees have different specs");
350
- return leaves.root;
351
- }
352
- const items = [...leaves];
353
- return this.builder.build(items, 0, items.length);
46
+ private wrap(record: SummaryTreeRecord<Leaf, Summary>): SummaryTree<Leaf, Summary> {
47
+ return record === this.record ? this : new SummaryTree(record);
354
48
  }
355
49
 
356
50
  /** The spec of the tree: its monoid and its measure. */
357
51
  get spec(): SummarySpec<Leaf, Summary> {
358
- return this.builder.spec;
52
+ return this.record.spec;
359
53
  }
360
54
 
361
55
  /** The number of leaves. */
362
56
  get size(): number {
363
- return sizeOf(this.root);
57
+ return Tree.size(this.record);
364
58
  }
365
59
 
366
60
  get isEmpty(): boolean {
367
- return this.root === null;
61
+ return Tree.isEmpty(this.record);
368
62
  }
369
63
 
370
64
  /** The summary of all the leaves, in their order. An empty tree has the summary `monoid.empty`. */
371
65
  get summary(): Summary {
372
- return this.builder.summaryOf(this.root);
66
+ return Tree.summary(this.record);
373
67
  }
374
68
 
375
69
  /** The height of the tree: 0 for an empty tree. The height is at most 1.45 log2(size + 2). */
376
70
  get height(): number {
377
- return heightOf(this.root);
71
+ return Tree.height(this.record);
378
72
  }
379
73
 
380
74
  /**
@@ -382,24 +76,22 @@ export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
382
76
  * from the end, as `Array.prototype.at` does.
383
77
  */
384
78
  at(index: number): Leaf | undefined {
385
- index = indexOf(index, this.size);
386
- return index === -1 ? undefined : this.builder.leafAt(this.root!, index);
79
+ return Tree.at(this.record, index);
387
80
  }
388
81
 
389
82
  /** This function gives the summary of the leaves from `start` to `end`, with `end` not included. */
390
83
  summaryOf(start = 0, end: number = this.size): Summary {
391
- return this.slice(start, end).summary;
84
+ return Tree.summaryOf(this.record, start, end);
392
85
  }
393
86
 
394
87
  /** This function gives the tree of the leaves of this tree, then the leaves of `other`. The two trees must have the same spec. */
395
88
  concat(other: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTree<Leaf, Summary> {
396
- const joined = this.builder.concat(this.root, this.treeOf(other));
397
- return this.wrap(this.builder.seam(joined, this.size - 1));
89
+ return this.wrap(Tree.concat(this.record, recordOf(other)));
398
90
  }
399
91
 
400
92
  /** This function splits the tree into its first `index` leaves and the other leaves. */
401
93
  splitAt(index: number): [SummaryTree<Leaf, Summary>, SummaryTree<Leaf, Summary>] {
402
- const [left, right] = this.builder.splitAt(this.root, clamp(index, this.size));
94
+ const [left, right] = Tree.splitAt(this.record, index);
403
95
  return [this.wrap(left), this.wrap(right)];
404
96
  }
405
97
 
@@ -409,7 +101,7 @@ export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
409
101
  * prefix. When no prefix satisfies it, the right tree is empty.
410
102
  */
411
103
  split(predicate: (prefix: Summary) => boolean): [SummaryTree<Leaf, Summary>, SummaryTree<Leaf, Summary>] {
412
- const [left, right] = this.builder.splitBy(this.root, predicate, this.builder.spec.monoid.empty);
104
+ const [left, right] = Tree.split(this.record, predicate);
413
105
  return [this.wrap(left), this.wrap(right)];
414
106
  }
415
107
 
@@ -418,23 +110,7 @@ export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
418
110
  * nothing. It gives `undefined` when no prefix satisfies the predicate.
419
111
  */
420
112
  search(predicate: (prefix: Summary) => boolean): SummarySearch<Leaf, Summary> | undefined {
421
- const { combine } = this.builder.spec.monoid;
422
- let node = this.root;
423
- let acc = this.builder.spec.monoid.empty;
424
- let index = 0;
425
- while (node !== null) {
426
- const throughLeft = node.left === null ? acc : combine(acc, node.left.summary);
427
- if (node.left !== null && predicate(throughLeft)) {
428
- node = node.left;
429
- continue;
430
- }
431
- const through = combine(throughLeft, node.own);
432
- if (predicate(through)) return { index: index + sizeOf(node.left), leaf: node.leaf, before: throughLeft, through };
433
- index += sizeOf(node.left) + 1;
434
- acc = through;
435
- node = node.right;
436
- }
437
- return undefined;
113
+ return Tree.search(this.record, predicate);
438
114
  }
439
115
 
440
116
  /**
@@ -448,37 +124,12 @@ export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
448
124
  * const at = rope.locate((s) => s.length, 1000);
449
125
  */
450
126
  locate(key: (summary: Summary) => number, target: number): SummaryLocation<Leaf> | undefined {
451
- if (!(target >= 0)) return undefined;
452
- let node = this.root;
453
- let index = 0;
454
- let rest = target;
455
- while (node !== null) {
456
- if (node.left !== null) {
457
- const left = key(node.left.summary);
458
- if (rest < left) {
459
- node = node.left;
460
- continue;
461
- }
462
- rest -= left;
463
- index += node.left.size;
464
- }
465
- const own = key(node.own);
466
- if (rest < own) return { index, leaf: node.leaf, offset: rest };
467
- rest -= own;
468
- index += 1;
469
- node = node.right;
470
- }
471
- return undefined;
127
+ return Tree.locate(this.record, key, target);
472
128
  }
473
129
 
474
130
  /** This function gives the tree of the leaves from `start` to `end`, with `end` not included. A negative index counts from the end. */
475
131
  slice(start = 0, end: number = this.size): SummaryTree<Leaf, Summary> {
476
- const from = clamp(start, this.size);
477
- const to = clamp(end, this.size);
478
- if (to <= from) return this.wrap(null);
479
- const [, rest] = this.builder.splitAt(this.root, from);
480
- const [middle] = this.builder.splitAt(rest, to - from);
481
- return this.wrap(middle);
132
+ return this.wrap(Tree.slice(this.record, start, end));
482
133
  }
483
134
 
484
135
  /**
@@ -486,46 +137,17 @@ export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
486
137
  * `Array.prototype.splice` does. It gives the new tree, not the removed leaves.
487
138
  */
488
139
  splice(start: number, deleteCount: number = this.size, inserted: SummaryTree<Leaf, Summary> | Iterable<Leaf> = []): SummaryTree<Leaf, Summary> {
489
- const from = clamp(start, this.size);
490
- const count = Math.max(0, Math.min(Number.isNaN(deleteCount) ? 0 : Math.trunc(deleteCount), this.size - from));
491
- const builder = this.builder;
492
- const leaves = inserted instanceof SummaryTree ? undefined : [...inserted];
493
- const added = leaves === undefined ? (inserted as SummaryTree<Leaf, Summary>).size : leaves.length;
494
- if (count === 0 && added === 0) return this;
495
- let root = this.root;
496
- if (leaves !== undefined && count + added <= SMALL_EDIT) {
497
- // A small edit copies only the paths to its leaves: 1 or 2 combines for each level of each path
498
- const replaced = Math.min(count, added);
499
- if (count > 0 && added > count) {
500
- // The last removed leaf takes all the extra leaves in one descent
501
- for (let i = 0; i < count - 1; i++) root = builder.replaceAt(root!, from + i, leaves[i]!, builder.spec.measure(leaves[i]!));
502
- root = builder.replaceSpan(root!, from + count - 1, leaves.slice(count - 1));
503
- } else for (let i = 0; i < added; i++) {
504
- const leaf = leaves[i]!;
505
- const own = builder.spec.measure(leaf);
506
- root = i < replaced ? builder.replaceAt(root!, from + i, leaf, own) : builder.insertAt(root, from + i, leaf, own);
507
- }
508
- for (let i = replaced; i < count; i++) root = builder.removeAt(root!, from + added);
509
- } else {
510
- const middle = leaves === undefined ? this.treeOf(inserted) : builder.build(leaves, 0, leaves.length);
511
- const [left, rest] = builder.splitAt(root, from);
512
- const [, right] = builder.splitAt(rest, count);
513
- root = builder.concat(builder.concat(left, middle), right);
514
- }
515
- // The right seam first, so that a merge there does not move the index of the left seam
516
- if (added > 0) root = builder.seam(root, from + added - 1);
517
- return this.wrap(builder.seam(root, from - 1));
140
+ return this.wrap(Tree.splice(this.record, start, deleteCount, recordOf(inserted)));
518
141
  }
519
142
 
520
143
  /** This function puts the leaves of `inserted` before the leaf at `index`. */
521
144
  insert(index: number, inserted: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTree<Leaf, Summary> {
522
- return this.splice(index, 0, inserted);
145
+ return this.wrap(Tree.insert(this.record, index, recordOf(inserted)));
523
146
  }
524
147
 
525
148
  /** This function removes the leaves from `start` to `end`, with `end` not included. */
526
149
  remove(start: number, end: number = this.size): SummaryTree<Leaf, Summary> {
527
- const from = clamp(start, this.size);
528
- return this.splice(from, Math.max(0, clamp(end, this.size) - from));
150
+ return this.wrap(Tree.remove(this.record, start, end));
529
151
  }
530
152
 
531
153
  /**
@@ -534,32 +156,35 @@ export class SummaryTree<Leaf, Summary> implements Iterable<Leaf> {
534
156
  * `spec.merge`.
535
157
  */
536
158
  set(index: number, leaf: Leaf): SummaryTree<Leaf, Summary> {
537
- const at = indexOf(index, this.size);
538
- return at === -1 ? this : this.wrap(this.builder.replaceAt(this.root!, at, leaf, this.builder.spec.measure(leaf)));
159
+ return this.wrap(Tree.set(this.record, index, leaf));
539
160
  }
540
161
 
541
162
  /** This function adds leaves after the last leaf. */
542
163
  append(...leaves: Leaf[]): SummaryTree<Leaf, Summary> {
543
- return this.concat(leaves);
164
+ return this.wrap(Tree.append(this.record, ...leaves));
544
165
  }
545
166
 
546
167
  /** This function adds leaves before the first leaf. */
547
168
  prepend(...leaves: Leaf[]): SummaryTree<Leaf, Summary> {
548
- const joined = this.builder.concat(this.treeOf(leaves), this.root);
549
- return this.wrap(this.builder.seam(joined, leaves.length - 1));
169
+ return this.wrap(Tree.prepend(this.record, ...leaves));
550
170
  }
551
171
 
552
172
  /** This function gives the leaves in their order. */
553
173
  [Symbol.iterator](): Iterator<Leaf> {
554
- return walk(this.root);
174
+ return Tree.leaves(this.record);
555
175
  }
556
176
 
557
177
  /** This function gives the leaves in an array. */
558
178
  toArray(): Leaf[] {
559
- return [...walk(this.root)];
179
+ return Tree.toArray(this.record);
560
180
  }
561
181
  }
562
182
 
183
+ /** This function gives the record of a tree, or the leaves when they are not a tree. */
184
+ function recordOf<Leaf, Summary>(leaves: SummaryTree<Leaf, Summary> | Iterable<Leaf>): SummaryTreeRecord<Leaf, Summary> | Iterable<Leaf> {
185
+ return leaves instanceof SummaryTree ? leaves.record : leaves;
186
+ }
187
+
563
188
  /**
564
189
  * This function makes a persistent tree of leaves with a summary of each part. Use the same `spec` object for each
565
190
  * tree that `concat` or `splice` joins.
@@ -572,10 +197,17 @@ export function summaryTree<Leaf, Summary>(spec: SummarySpec<Leaf, Summary>, lea
572
197
  * @internal This function examines the invariants of a tree: the AVL balance, the heights, the sizes and the
573
198
  * summaries. It gives a list of the faults, empty when there is no fault. The tests use it.
574
199
  */
575
- export function summaryTreeFaults<Leaf, Summary>(tree: SummaryTree<Leaf, Summary>, equal: (a: Summary, b: Summary) => boolean): string[] {
576
- const builder = tree["builder"];
200
+ export function summaryTreeFaults<Leaf, Summary>(
201
+ tree: SummaryTree<Leaf, Summary> | SummaryTreeRecord<Leaf, Summary>,
202
+ equal: (a: Summary, b: Summary) => boolean,
203
+ ): string[] {
204
+ const { spec, root } = tree instanceof SummaryTree ? tree.record : tree;
205
+ const { combine, empty } = spec.monoid;
206
+ const heightOf = (n: SummaryNode<Leaf, Summary> | null): number => (n === null ? 0 : n.height);
207
+ const sizeOf = (n: SummaryNode<Leaf, Summary> | null): number => (n === null ? 0 : n.size);
208
+ const summaryOf = (n: SummaryNode<Leaf, Summary> | null): Summary => (n === null ? empty : n.summary);
577
209
  const faults: string[] = [];
578
- const visit = (node: Tree<Leaf, Summary>, path: string): void => {
210
+ const visit = (node: SummaryNode<Leaf, Summary> | null, path: string): void => {
579
211
  if (node === null) return;
580
212
  visit(node.left, `${path}L`);
581
213
  visit(node.right, `${path}R`);
@@ -584,11 +216,10 @@ export function summaryTreeFaults<Leaf, Summary>(tree: SummaryTree<Leaf, Summary
584
216
  if (Math.abs(hl - hr) > 1) faults.push(`${path}: balance ${hl - hr}`);
585
217
  if (node.height !== 1 + Math.max(hl, hr)) faults.push(`${path}: height ${node.height}`);
586
218
  if (node.size !== sizeOf(node.left) + 1 + sizeOf(node.right)) faults.push(`${path}: size ${node.size}`);
587
- const { combine } = builder.spec.monoid;
588
- const inner = combine(builder.summaryOf(node.left), builder.spec.measure(node.leaf));
219
+ const inner = combine(summaryOf(node.left), spec.measure(node.leaf));
589
220
  if (!equal(node.inner, inner)) faults.push(`${path}: inner`);
590
- if (!equal(node.summary, combine(inner, builder.summaryOf(node.right)))) faults.push(`${path}: summary`);
221
+ if (!equal(node.summary, combine(inner, summaryOf(node.right)))) faults.push(`${path}: summary`);
591
222
  };
592
- visit(tree["root"], "^");
223
+ visit(root, "^");
593
224
  return faults;
594
225
  }