@mark1russell7/collections 0.0.0-bootstrap.0 → 0.1.0

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -1
  3. package/build/dag/index.d.ts +144 -0
  4. package/build/dag/index.d.ts.map +1 -0
  5. package/build/dag/index.js +294 -0
  6. package/build/dag/index.js.map +1 -0
  7. package/build/graph/index.d.ts +20 -0
  8. package/build/graph/index.d.ts.map +1 -0
  9. package/build/graph/index.js +48 -0
  10. package/build/graph/index.js.map +1 -0
  11. package/build/index.d.ts +4952 -0
  12. package/build/index.d.ts.map +1 -0
  13. package/build/index.js +7811 -0
  14. package/build/index.js.map +1 -0
  15. package/build/testing/index.d.ts +25 -0
  16. package/build/testing/index.d.ts.map +1 -0
  17. package/build/testing/index.js +72 -0
  18. package/build/testing/index.js.map +1 -0
  19. package/package.json +71 -4
  20. package/src/async/async-queue.ts +481 -0
  21. package/src/async/channels.ts +450 -0
  22. package/src/async/settled.ts +41 -0
  23. package/src/behaviors/bounded.ts +485 -0
  24. package/src/behaviors/composite.ts +99 -0
  25. package/src/behaviors/evented.ts +464 -0
  26. package/src/behaviors/lru.ts +449 -0
  27. package/src/behaviors/readonly.ts +236 -0
  28. package/src/behaviors/safe.ts +358 -0
  29. package/src/behaviors/synchronized.ts +316 -0
  30. package/src/behaviors/ttl.ts +464 -0
  31. package/src/core/effects.ts +327 -0
  32. package/src/core/events.ts +363 -0
  33. package/src/core/middleware.ts +413 -0
  34. package/src/core/policies.ts +316 -0
  35. package/src/core/traits.ts +164 -0
  36. package/src/dag/builder.ts +124 -0
  37. package/src/dag/executor.ts +190 -0
  38. package/src/dag/index.ts +14 -0
  39. package/src/dag/traversal.ts +129 -0
  40. package/src/dag/types.ts +87 -0
  41. package/src/fx/collectors.ts +500 -0
  42. package/src/fx/iter.ts +536 -0
  43. package/src/graph/hub-order.ts +53 -0
  44. package/src/graph/index.ts +5 -0
  45. package/src/impl/array-deque.ts +463 -0
  46. package/src/impl/array-list.ts +490 -0
  47. package/src/impl/hash-map.ts +623 -0
  48. package/src/impl/hash-set.ts +342 -0
  49. package/src/impl/linked-hash-map.ts +572 -0
  50. package/src/impl/linked-list.ts +610 -0
  51. package/src/impl/priority-queue.ts +448 -0
  52. package/src/impl/summary-tree.ts +594 -0
  53. package/src/impl/tree-map.ts +913 -0
  54. package/src/impl/tree-set.ts +469 -0
  55. package/src/index.ts +237 -0
  56. package/src/interfaces/collection.ts +141 -0
  57. package/src/interfaces/list.ts +281 -0
  58. package/src/interfaces/map.ts +405 -0
  59. package/src/interfaces/queue.ts +353 -0
  60. package/src/interfaces/set.ts +158 -0
  61. package/src/order/index.ts +6 -0
  62. package/src/order/rank.ts +271 -0
  63. package/src/storage/listeners.ts +72 -0
  64. package/src/testing/check.ts +81 -0
  65. package/src/testing/index.ts +7 -0
  66. package/src/utils/defaults.ts +345 -0
  67. package/src/utils/factories.ts +357 -0
  68. package/src/utils/helpers.ts +248 -0
@@ -0,0 +1,913 @@
1
+ /**
2
+ * TreeMap - Red-black tree based sorted map implementation.
3
+ *
4
+ * This module implements a self-balancing binary search tree that maintains keys in sorted
5
+ * order. Mirrors java.util.TreeMap.
6
+ *
7
+ * Key features:
8
+ * - O(log n) access, insert, delete
9
+ * - Keys maintained in sorted order (natural or custom comparator)
10
+ * - Navigation methods (floor, ceiling, lower, higher)
11
+ * - Range view operations (subMap, headMap, tailMap)
12
+ *
13
+ * @example
14
+ * const map = treeMap<string, number>()
15
+ * map.set('c', 3)
16
+ * map.set('a', 1)
17
+ * map.set('b', 2)
18
+ * // Iteration order: a, b, c (sorted)
19
+ *
20
+ * @example
21
+ * // Custom comparator for descending order
22
+ * const map = treeMap<number, string>({
23
+ * compare: (a, b) => b - a
24
+ * })
25
+ */
26
+
27
+ import type { NavigableMap, SortedMap, Entry } from "../interfaces/map.js";
28
+ import type { Eq, Compare } from "../core/traits.js";
29
+ import { defaultEq, defaultCompare } from "../utils/defaults.js";
30
+
31
+ /**
32
+ * Node color in red-black tree.
33
+ */
34
+ const Color = {
35
+ RED: "RED",
36
+ BLACK: "BLACK",
37
+ } as const;
38
+ type Color = (typeof Color)[keyof typeof Color];
39
+
40
+ /**
41
+ * Node in the red-black tree.
42
+ */
43
+ interface TreeNode<K, V> {
44
+ key: K;
45
+ value: V;
46
+ color: Color;
47
+ left: TreeNode<K, V> | null;
48
+ right: TreeNode<K, V> | null;
49
+ parent: TreeNode<K, V> | null;
50
+ }
51
+
52
+ // Null-safe helpers of the red-black algorithms: a null leaf is black
53
+ function colorOf<K, V>(node: TreeNode<K, V> | null): Color {
54
+ return node === null ? Color.BLACK : node.color;
55
+ }
56
+ function parentOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {
57
+ return node === null ? null : node.parent;
58
+ }
59
+ function leftOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {
60
+ return node === null ? null : node.left;
61
+ }
62
+ function rightOf<K, V>(node: TreeNode<K, V> | null): TreeNode<K, V> | null {
63
+ return node === null ? null : node.right;
64
+ }
65
+ function setColor<K, V>(node: TreeNode<K, V> | null, color: Color): void {
66
+ if (node !== null) node.color = color;
67
+ }
68
+
69
+ /**
70
+ * Options for making a TreeMap.
71
+ */
72
+ export interface TreeMapOptions<K, V> {
73
+ /**
74
+ * Comparison function for keys.
75
+ * @default defaultCompare
76
+ */
77
+ compare?: Compare<K>;
78
+
79
+ /**
80
+ * Equality function for keys.
81
+ * @default defaultEq
82
+ */
83
+ eq?: Eq<K>;
84
+
85
+ /**
86
+ * Equality function for values.
87
+ * @default defaultEq
88
+ */
89
+ valueEq?: Eq<V>;
90
+ }
91
+
92
+ /**
93
+ * TreeMap<K, V> - Red-black tree based sorted map.
94
+ *
95
+ * Maintains keys in sorted order using a self-balancing binary search tree.
96
+ * This class gives O(log n) operations and navigation methods.
97
+ */
98
+ export class TreeMap<K, V> implements NavigableMap<K, V> {
99
+ private _root: TreeNode<K, V> | null = null;
100
+ private _size: number = 0;
101
+ private readonly _compare: Compare<K>;
102
+ private readonly _eq: Eq<K>;
103
+ private readonly _valueEq: Eq<V>;
104
+
105
+ constructor(options: TreeMapOptions<K, V> = {}) {
106
+ const {
107
+ compare = defaultCompare,
108
+ eq = defaultEq,
109
+ valueEq = defaultEq,
110
+ } = options;
111
+
112
+ this._compare = compare;
113
+ this._eq = eq;
114
+ this._valueEq = valueEq;
115
+ }
116
+
117
+ // ========================================================================
118
+ // Size and state
119
+ // ========================================================================
120
+
121
+ get size(): number {
122
+ return this._size;
123
+ }
124
+
125
+ get isEmpty(): boolean {
126
+ return this._size === 0;
127
+ }
128
+
129
+ get comparator(): Compare<K> {
130
+ return this._compare;
131
+ }
132
+
133
+ get keyEq(): Eq<K> {
134
+ return this._eq;
135
+ }
136
+
137
+ get valueEq(): Eq<V> {
138
+ return this._valueEq;
139
+ }
140
+
141
+ // ========================================================================
142
+ // Lookup operations
143
+ // ========================================================================
144
+
145
+ has(key: K): boolean {
146
+ return this.getNode(key) !== null;
147
+ }
148
+
149
+ containsKey(key: K): boolean {
150
+ return this.has(key);
151
+ }
152
+
153
+ containsValue(value: V): boolean {
154
+ return this.findValue(this._root, value);
155
+ }
156
+
157
+ get(key: K): V {
158
+ const node = this.getNode(key);
159
+ if (node === null) {
160
+ throw new Error("Key not found");
161
+ }
162
+ return node.value;
163
+ }
164
+
165
+ getOrUndefined(key: K): V | undefined {
166
+ const node = this.getNode(key);
167
+ return node?.value;
168
+ }
169
+
170
+ getOrDefault(key: K, defaultValue: V): V {
171
+ const node = this.getNode(key);
172
+ return node !== null ? node.value : defaultValue;
173
+ }
174
+
175
+ // ========================================================================
176
+ // Modification operations
177
+ // ========================================================================
178
+
179
+ set(key: K, value: V): V | undefined {
180
+ if (this._root === null) {
181
+ this._root = this.createNode(key, value, Color.BLACK);
182
+ this._size++;
183
+ return undefined;
184
+ }
185
+
186
+ // Find insertion point
187
+ let node: TreeNode<K, V> | null = this._root;
188
+ let parent: TreeNode<K, V> | null = null;
189
+
190
+ while (node !== null) {
191
+ parent = node;
192
+ const cmp = this._compare(key, node.key);
193
+
194
+ if (cmp === 0) {
195
+ // Key exists, replace value
196
+ const oldValue = node.value;
197
+ node.value = value;
198
+ return oldValue;
199
+ } else if (cmp < 0) {
200
+ node = node.left;
201
+ } else {
202
+ node = node.right;
203
+ }
204
+ }
205
+
206
+ // Insert new node
207
+ const newNode = this.createNode(key, value, Color.RED);
208
+ newNode.parent = parent;
209
+
210
+ if (parent !== null) {
211
+ const cmp = this._compare(key, parent.key);
212
+ if (cmp < 0) {
213
+ parent.left = newNode;
214
+ } else {
215
+ parent.right = newNode;
216
+ }
217
+ }
218
+
219
+ this._size++;
220
+ this.fixAfterInsertion(newNode);
221
+ return undefined;
222
+ }
223
+
224
+ setIfAbsent(key: K, value: V): V {
225
+ const existing = this.getNode(key);
226
+ if (existing !== null) {
227
+ return existing.value;
228
+ }
229
+ this.set(key, value);
230
+ return value;
231
+ }
232
+
233
+ replace(key: K, value: V): V | undefined {
234
+ const node = this.getNode(key);
235
+ if (node === null) return undefined;
236
+ const oldValue = node.value;
237
+ node.value = value;
238
+ return oldValue;
239
+ }
240
+
241
+ replaceEntry(key: K, oldValue: V, newValue: V): boolean {
242
+ const node = this.getNode(key);
243
+ if (node === null || !this._valueEq(node.value, oldValue)) {
244
+ return false;
245
+ }
246
+ node.value = newValue;
247
+ return true;
248
+ }
249
+
250
+ delete(key: K): V | undefined {
251
+ const node = this.getNode(key);
252
+ if (node === null) return undefined;
253
+
254
+ const oldValue = node.value;
255
+ this.deleteNode(node);
256
+ this._size--;
257
+ return oldValue;
258
+ }
259
+
260
+ deleteEntry(key: K, value: V): boolean {
261
+ const node = this.getNode(key);
262
+ if (node === null || !this._valueEq(node.value, value)) {
263
+ return false;
264
+ }
265
+ this.deleteNode(node);
266
+ this._size--;
267
+ return true;
268
+ }
269
+
270
+ clear(): void {
271
+ this._root = null;
272
+ this._size = 0;
273
+ }
274
+
275
+ // ========================================================================
276
+ // Bulk operations
277
+ // ========================================================================
278
+
279
+ putAll(other: NavigableMap<K, V> | Iterable<Entry<K, V>>): void {
280
+ if ('entries' in other && typeof other.entries === 'function') {
281
+ for (const entry of other.entries()) {
282
+ this.set(entry.key, entry.value);
283
+ }
284
+ } else {
285
+ for (const entry of other as Iterable<Entry<K, V>>) {
286
+ this.set(entry.key, entry.value);
287
+ }
288
+ }
289
+ }
290
+
291
+ // ========================================================================
292
+ // Computed operations
293
+ // ========================================================================
294
+
295
+ computeIfAbsent(key: K, mappingFunction: (key: K) => V): V {
296
+ const existing = this.getNode(key);
297
+ if (existing !== null) {
298
+ return existing.value;
299
+ }
300
+ const value = mappingFunction(key);
301
+ this.set(key, value);
302
+ return value;
303
+ }
304
+
305
+ computeIfPresent(key: K, remappingFunction: (key: K, value: V) => V | undefined): V | undefined {
306
+ const existing = this.getNode(key);
307
+ if (existing === null) return undefined;
308
+
309
+ const newValue = remappingFunction(key, existing.value);
310
+ if (newValue === undefined) {
311
+ this.delete(key);
312
+ return undefined;
313
+ }
314
+ existing.value = newValue;
315
+ return newValue;
316
+ }
317
+
318
+ compute(key: K, remappingFunction: (key: K, value: V | undefined) => V | undefined): V | undefined {
319
+ const existing = this.getNode(key);
320
+ const newValue = remappingFunction(key, existing?.value);
321
+
322
+ if (newValue === undefined) {
323
+ if (existing !== null) {
324
+ this.delete(key);
325
+ }
326
+ return undefined;
327
+ }
328
+
329
+ this.set(key, newValue);
330
+ return newValue;
331
+ }
332
+
333
+ merge(key: K, value: V, remappingFunction: (oldValue: V, newValue: V) => V | undefined): V | undefined {
334
+ const existing = this.getNode(key);
335
+
336
+ if (existing === null) {
337
+ this.set(key, value);
338
+ return value;
339
+ }
340
+
341
+ const merged = remappingFunction(existing.value, value);
342
+ if (merged === undefined) {
343
+ this.delete(key);
344
+ return undefined;
345
+ }
346
+
347
+ existing.value = merged;
348
+ return merged;
349
+ }
350
+
351
+ // ========================================================================
352
+ // SortedMap operations
353
+ // ========================================================================
354
+
355
+ firstKey(): K {
356
+ if (this._root === null) {
357
+ throw new Error("Map is empty");
358
+ }
359
+ return this.getFirstNode(this._root).key;
360
+ }
361
+
362
+ lastKey(): K {
363
+ if (this._root === null) {
364
+ throw new Error("Map is empty");
365
+ }
366
+ return this.getLastNode(this._root).key;
367
+ }
368
+
369
+ headMap(toKey: K): SortedMap<K, V> {
370
+ // Return a view (simplified: create new map with filtered entries)
371
+ const result = new TreeMap<K, V>({
372
+ compare: this._compare,
373
+ eq: this._eq,
374
+ valueEq: this._valueEq,
375
+ });
376
+
377
+ for (const entry of this.entries()) {
378
+ if (this._compare(entry.key, toKey) < 0) {
379
+ result.set(entry.key, entry.value);
380
+ } else {
381
+ break; // Keys are sorted, so we can stop
382
+ }
383
+ }
384
+
385
+ return result;
386
+ }
387
+
388
+ tailMap(fromKey: K): SortedMap<K, V> {
389
+ const result = new TreeMap<K, V>({
390
+ compare: this._compare,
391
+ eq: this._eq,
392
+ valueEq: this._valueEq,
393
+ });
394
+
395
+ let started = false;
396
+ for (const entry of this.entries()) {
397
+ if (!started && this._compare(entry.key, fromKey) < 0) {
398
+ continue;
399
+ }
400
+ started = true;
401
+ result.set(entry.key, entry.value);
402
+ }
403
+
404
+ return result;
405
+ }
406
+
407
+ subMap(fromKey: K, toKey: K): SortedMap<K, V> {
408
+ const result = new TreeMap<K, V>({
409
+ compare: this._compare,
410
+ eq: this._eq,
411
+ valueEq: this._valueEq,
412
+ });
413
+
414
+ for (const entry of this.entries()) {
415
+ const cmpFrom = this._compare(entry.key, fromKey);
416
+ const cmpTo = this._compare(entry.key, toKey);
417
+
418
+ if (cmpFrom >= 0 && cmpTo < 0) {
419
+ result.set(entry.key, entry.value);
420
+ } else if (cmpTo >= 0) {
421
+ break; // Past the range
422
+ }
423
+ }
424
+
425
+ return result;
426
+ }
427
+
428
+ // ========================================================================
429
+ // NavigableMap operations
430
+ // ========================================================================
431
+
432
+ floorKey(key: K): K | undefined {
433
+ return this.floorEntry(key)?.key;
434
+ }
435
+
436
+ ceilingKey(key: K): K | undefined {
437
+ return this.ceilingEntry(key)?.key;
438
+ }
439
+
440
+ lowerKey(key: K): K | undefined {
441
+ return this.lowerEntry(key)?.key;
442
+ }
443
+
444
+ higherKey(key: K): K | undefined {
445
+ return this.higherEntry(key)?.key;
446
+ }
447
+
448
+ floorEntry(key: K): Entry<K, V> | undefined {
449
+ let node = this._root;
450
+ let result: TreeNode<K, V> | null = null;
451
+
452
+ while (node !== null) {
453
+ const cmp = this._compare(key, node.key);
454
+ if (cmp === 0) {
455
+ return { key: node.key, value: node.value };
456
+ } else if (cmp < 0) {
457
+ node = node.left;
458
+ } else {
459
+ result = node; // This node is <= key
460
+ node = node.right;
461
+ }
462
+ }
463
+
464
+ return result ? { key: result.key, value: result.value } : undefined;
465
+ }
466
+
467
+ ceilingEntry(key: K): Entry<K, V> | undefined {
468
+ let node = this._root;
469
+ let result: TreeNode<K, V> | null = null;
470
+
471
+ while (node !== null) {
472
+ const cmp = this._compare(key, node.key);
473
+ if (cmp === 0) {
474
+ return { key: node.key, value: node.value };
475
+ } else if (cmp > 0) {
476
+ node = node.right;
477
+ } else {
478
+ result = node; // This node is >= key
479
+ node = node.left;
480
+ }
481
+ }
482
+
483
+ return result ? { key: result.key, value: result.value } : undefined;
484
+ }
485
+
486
+ lowerEntry(key: K): Entry<K, V> | undefined {
487
+ let node = this._root;
488
+ let result: TreeNode<K, V> | null = null;
489
+
490
+ while (node !== null) {
491
+ const cmp = this._compare(key, node.key);
492
+ if (cmp <= 0) {
493
+ node = node.left;
494
+ } else {
495
+ result = node; // This node is < key
496
+ node = node.right;
497
+ }
498
+ }
499
+
500
+ return result ? { key: result.key, value: result.value } : undefined;
501
+ }
502
+
503
+ higherEntry(key: K): Entry<K, V> | undefined {
504
+ let node = this._root;
505
+ let result: TreeNode<K, V> | null = null;
506
+
507
+ while (node !== null) {
508
+ const cmp = this._compare(key, node.key);
509
+ if (cmp >= 0) {
510
+ node = node.right;
511
+ } else {
512
+ result = node; // This node is > key
513
+ node = node.left;
514
+ }
515
+ }
516
+
517
+ return result ? { key: result.key, value: result.value } : undefined;
518
+ }
519
+
520
+ firstEntry(): Entry<K, V> | undefined {
521
+ if (this._root === null) return undefined;
522
+ const node = this.getFirstNode(this._root);
523
+ return { key: node.key, value: node.value };
524
+ }
525
+
526
+ lastEntry(): Entry<K, V> | undefined {
527
+ if (this._root === null) return undefined;
528
+ const node = this.getLastNode(this._root);
529
+ return { key: node.key, value: node.value };
530
+ }
531
+
532
+ pollFirstEntry(): Entry<K, V> | undefined {
533
+ if (this._root === null) return undefined;
534
+ const node = this.getFirstNode(this._root);
535
+ const entry = { key: node.key, value: node.value };
536
+ this.deleteNode(node);
537
+ this._size--;
538
+ return entry;
539
+ }
540
+
541
+ pollLastEntry(): Entry<K, V> | undefined {
542
+ if (this._root === null) return undefined;
543
+ const node = this.getLastNode(this._root);
544
+ const entry = { key: node.key, value: node.value };
545
+ this.deleteNode(node);
546
+ this._size--;
547
+ return entry;
548
+ }
549
+
550
+ descendingMap(): NavigableMap<K, V> {
551
+ // Create a new TreeMap with reversed comparator
552
+ const reversed = new TreeMap<K, V>({
553
+ compare: (a, b) => this._compare(b, a),
554
+ eq: this._eq,
555
+ valueEq: this._valueEq,
556
+ });
557
+
558
+ for (const entry of this.entries()) {
559
+ reversed.set(entry.key, entry.value);
560
+ }
561
+
562
+ return reversed;
563
+ }
564
+
565
+ *descendingKeys(): IterableIterator<K> {
566
+ yield* this.reverseInOrderTraversal(this._root, (node) => node.key);
567
+ }
568
+
569
+ // ========================================================================
570
+ // View operations
571
+ // ========================================================================
572
+
573
+ *keys(): IterableIterator<K> {
574
+ yield* this.inOrderTraversal(this._root, (node) => node.key);
575
+ }
576
+
577
+ *values(): IterableIterator<V> {
578
+ yield* this.inOrderTraversal(this._root, (node) => node.value);
579
+ }
580
+
581
+ *entries(): IterableIterator<Entry<K, V>> {
582
+ yield* this.inOrderTraversal(this._root, (node) => ({
583
+ key: node.key,
584
+ value: node.value,
585
+ }));
586
+ }
587
+
588
+ *[Symbol.iterator](): Iterator<Entry<K, V>> {
589
+ yield* this.entries();
590
+ }
591
+
592
+ forEach(action: (value: V, key: K, map: this) => void): void {
593
+ for (const entry of this.entries()) {
594
+ action(entry.value, entry.key, this);
595
+ }
596
+ }
597
+
598
+ toArray(): Entry<K, V>[] {
599
+ return Array.from(this.entries());
600
+ }
601
+
602
+ // ========================================================================
603
+ // Private helpers - Tree operations
604
+ // ========================================================================
605
+
606
+ private createNode(key: K, value: V, color: Color): TreeNode<K, V> {
607
+ return {
608
+ key,
609
+ value,
610
+ color,
611
+ left: null,
612
+ right: null,
613
+ parent: null,
614
+ };
615
+ }
616
+
617
+ private getNode(key: K): TreeNode<K, V> | null {
618
+ let node = this._root;
619
+
620
+ while (node !== null) {
621
+ const cmp = this._compare(key, node.key);
622
+ if (cmp === 0) {
623
+ return node;
624
+ } else if (cmp < 0) {
625
+ node = node.left;
626
+ } else {
627
+ node = node.right;
628
+ }
629
+ }
630
+
631
+ return null;
632
+ }
633
+
634
+ private getFirstNode(node: TreeNode<K, V>): TreeNode<K, V> {
635
+ while (node.left !== null) {
636
+ node = node.left;
637
+ }
638
+ return node;
639
+ }
640
+
641
+ private getLastNode(node: TreeNode<K, V>): TreeNode<K, V> {
642
+ while (node.right !== null) {
643
+ node = node.right;
644
+ }
645
+ return node;
646
+ }
647
+
648
+ private findValue(node: TreeNode<K, V> | null, value: V): boolean {
649
+ if (node === null) return false;
650
+ if (this._valueEq(node.value, value)) return true;
651
+ return this.findValue(node.left, value) || this.findValue(node.right, value);
652
+ }
653
+
654
+ private *inOrderTraversal<T>(
655
+ node: TreeNode<K, V> | null,
656
+ mapper: (node: TreeNode<K, V>) => T
657
+ ): IterableIterator<T> {
658
+ if (node === null) return;
659
+ yield* this.inOrderTraversal(node.left, mapper);
660
+ yield mapper(node);
661
+ yield* this.inOrderTraversal(node.right, mapper);
662
+ }
663
+
664
+ private *reverseInOrderTraversal<T>(
665
+ node: TreeNode<K, V> | null,
666
+ mapper: (node: TreeNode<K, V>) => T
667
+ ): IterableIterator<T> {
668
+ if (node === null) return;
669
+ yield* this.reverseInOrderTraversal(node.right, mapper);
670
+ yield mapper(node);
671
+ yield* this.reverseInOrderTraversal(node.left, mapper);
672
+ }
673
+
674
+ // ========================================================================
675
+ // Private helpers - Red-black tree balancing
676
+ // ========================================================================
677
+
678
+ private rotateLeft(node: TreeNode<K, V> | null): void {
679
+ if (node === null || node.right === null) return;
680
+ const right = node.right;
681
+ node.right = right.left;
682
+
683
+ if (right.left !== null) {
684
+ right.left.parent = node;
685
+ }
686
+
687
+ right.parent = node.parent;
688
+
689
+ if (node.parent === null) {
690
+ this._root = right;
691
+ } else if (node === node.parent.left) {
692
+ node.parent.left = right;
693
+ } else {
694
+ node.parent.right = right;
695
+ }
696
+
697
+ right.left = node;
698
+ node.parent = right;
699
+ }
700
+
701
+ private rotateRight(node: TreeNode<K, V> | null): void {
702
+ if (node === null || node.left === null) return;
703
+ const left = node.left;
704
+ node.left = left.right;
705
+
706
+ if (left.right !== null) {
707
+ left.right.parent = node;
708
+ }
709
+
710
+ left.parent = node.parent;
711
+
712
+ if (node.parent === null) {
713
+ this._root = left;
714
+ } else if (node === node.parent.right) {
715
+ node.parent.right = left;
716
+ } else {
717
+ node.parent.left = left;
718
+ }
719
+
720
+ left.right = node;
721
+ node.parent = left;
722
+ }
723
+
724
+ private fixAfterInsertion(node: TreeNode<K, V>): void {
725
+ while (node.parent !== null && node.parent.color === Color.RED) {
726
+ if (node.parent === node.parent.parent?.left) {
727
+ const uncle = node.parent.parent.right;
728
+
729
+ if (uncle?.color === Color.RED) {
730
+ // Case 1: Uncle is red
731
+ node.parent.color = Color.BLACK;
732
+ uncle.color = Color.BLACK;
733
+ node.parent.parent.color = Color.RED;
734
+ node = node.parent.parent;
735
+ } else {
736
+ if (node === node.parent.right) {
737
+ // Case 2: Node is right child
738
+ node = node.parent;
739
+ this.rotateLeft(node);
740
+ }
741
+ // Case 3: Node is left child
742
+ node.parent!.color = Color.BLACK;
743
+ node.parent!.parent!.color = Color.RED;
744
+ this.rotateRight(node.parent!.parent!);
745
+ }
746
+ } else {
747
+ const uncle = node.parent.parent?.left ?? null;
748
+
749
+ if (uncle?.color === Color.RED) {
750
+ // Case 1: Uncle is red
751
+ node.parent.color = Color.BLACK;
752
+ uncle.color = Color.BLACK;
753
+ node.parent.parent!.color = Color.RED;
754
+ node = node.parent.parent!;
755
+ } else {
756
+ if (node === node.parent.left) {
757
+ // Case 2: Node is left child
758
+ node = node.parent;
759
+ this.rotateRight(node);
760
+ }
761
+ // Case 3: Node is right child
762
+ node.parent!.color = Color.BLACK;
763
+ node.parent!.parent!.color = Color.RED;
764
+ this.rotateLeft(node.parent!.parent!);
765
+ }
766
+ }
767
+ }
768
+
769
+ this._root!.color = Color.BLACK;
770
+ }
771
+
772
+ /**
773
+ * This method deletes a node (the CLRS algorithm, as in java.util.TreeMap). A null leaf counts as black.
774
+ *
775
+ * Before (BUGS-2026-07 L10): the deletion of a black leaf skipped the fix-up, so the black
776
+ * heights drifted and the tree became unbalanced. Also, the fix-up treated a null leaf as
777
+ * "not black", so it chose the wrong case and rotated at null (a TypeError).
778
+ */
779
+ private deleteNode(target: TreeNode<K, V>): void {
780
+ let node = target;
781
+ // A node with two children takes the key and value of its successor, then the successor goes
782
+ if (node.left !== null && node.right !== null) {
783
+ const successor = this.getFirstNode(node.right);
784
+ node.key = successor.key;
785
+ node.value = successor.value;
786
+ node = successor;
787
+ }
788
+
789
+ const replacement = node.left ?? node.right;
790
+ if (replacement !== null) {
791
+ replacement.parent = node.parent;
792
+ if (node.parent === null) this._root = replacement;
793
+ else if (node === node.parent.left) node.parent.left = replacement;
794
+ else node.parent.right = replacement;
795
+ node.left = node.right = node.parent = null;
796
+ if (node.color === Color.BLACK) this.fixAfterDeletion(replacement);
797
+ } else if (node.parent === null) {
798
+ // The only node
799
+ this._root = null;
800
+ } else {
801
+ // A leaf: it is its own phantom replacement during the fix-up, then it goes
802
+ if (node.color === Color.BLACK) this.fixAfterDeletion(node);
803
+ if (node.parent !== null) {
804
+ if (node === node.parent.left) node.parent.left = null;
805
+ else if (node === node.parent.right) node.parent.right = null;
806
+ node.parent = null;
807
+ }
808
+ }
809
+ }
810
+
811
+ private fixAfterDeletion(start: TreeNode<K, V>): void {
812
+ let x: TreeNode<K, V> | null = start;
813
+ while (x !== this._root && colorOf(x) === Color.BLACK) {
814
+ if (x === leftOf(parentOf(x))) {
815
+ let sibling = rightOf(parentOf(x));
816
+ if (colorOf(sibling) === Color.RED) {
817
+ setColor(sibling, Color.BLACK);
818
+ setColor(parentOf(x), Color.RED);
819
+ this.rotateLeft(parentOf(x));
820
+ sibling = rightOf(parentOf(x));
821
+ }
822
+ if (colorOf(leftOf(sibling)) === Color.BLACK && colorOf(rightOf(sibling)) === Color.BLACK) {
823
+ setColor(sibling, Color.RED);
824
+ x = parentOf(x);
825
+ } else {
826
+ if (colorOf(rightOf(sibling)) === Color.BLACK) {
827
+ setColor(leftOf(sibling), Color.BLACK);
828
+ setColor(sibling, Color.RED);
829
+ this.rotateRight(sibling);
830
+ sibling = rightOf(parentOf(x));
831
+ }
832
+ setColor(sibling, colorOf(parentOf(x)));
833
+ setColor(parentOf(x), Color.BLACK);
834
+ setColor(rightOf(sibling), Color.BLACK);
835
+ this.rotateLeft(parentOf(x));
836
+ x = this._root;
837
+ }
838
+ } else {
839
+ let sibling = leftOf(parentOf(x));
840
+ if (colorOf(sibling) === Color.RED) {
841
+ setColor(sibling, Color.BLACK);
842
+ setColor(parentOf(x), Color.RED);
843
+ this.rotateRight(parentOf(x));
844
+ sibling = leftOf(parentOf(x));
845
+ }
846
+ if (colorOf(rightOf(sibling)) === Color.BLACK && colorOf(leftOf(sibling)) === Color.BLACK) {
847
+ setColor(sibling, Color.RED);
848
+ x = parentOf(x);
849
+ } else {
850
+ if (colorOf(leftOf(sibling)) === Color.BLACK) {
851
+ setColor(rightOf(sibling), Color.BLACK);
852
+ setColor(sibling, Color.RED);
853
+ this.rotateLeft(sibling);
854
+ sibling = leftOf(parentOf(x));
855
+ }
856
+ setColor(sibling, colorOf(parentOf(x)));
857
+ setColor(parentOf(x), Color.BLACK);
858
+ setColor(leftOf(sibling), Color.BLACK);
859
+ this.rotateRight(parentOf(x));
860
+ x = this._root;
861
+ }
862
+ }
863
+ }
864
+ setColor(x, Color.BLACK);
865
+ }
866
+
867
+ // ========================================================================
868
+ // Utility methods
869
+ // ========================================================================
870
+
871
+ toString(): string {
872
+ const entries = Array.from(this.entries())
873
+ .map(({ key, value }) => `${key}=${value}`)
874
+ .join(', ');
875
+ return `TreeMap{${entries}}`;
876
+ }
877
+ }
878
+
879
+ /**
880
+ * Factory function to make a TreeMap.
881
+ *
882
+ * @example
883
+ * const map = treeMap<string, number>()
884
+ * map.set('c', 3)
885
+ * map.set('a', 1)
886
+ * map.set('b', 2)
887
+ * // Iteration order: a, b, c
888
+ *
889
+ * @example
890
+ * // With initial entries
891
+ * const map = treeMap<string, number>([
892
+ * ['c', 3],
893
+ * ['a', 1],
894
+ * ['b', 2]
895
+ * ])
896
+ *
897
+ * @example
898
+ * // Custom comparator for descending order
899
+ * const map = treeMap<number, string>({ compare: (a, b) => b - a })
900
+ */
901
+ export function treeMap<K, V>(
902
+ optionsOrEntries?: TreeMapOptions<K, V> | Iterable<[K, V]>
903
+ ): TreeMap<K, V> {
904
+ if (optionsOrEntries && Symbol.iterator in optionsOrEntries) {
905
+ const map = new TreeMap<K, V>();
906
+ for (const [key, value] of optionsOrEntries as Iterable<[K, V]>) {
907
+ map.set(key, value);
908
+ }
909
+ return map;
910
+ }
911
+
912
+ return new TreeMap<K, V>(optionsOrEntries as TreeMapOptions<K, V>);
913
+ }