sorted-collections 1.0.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Johans Neira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,258 @@
1
+ <a id="readme-top"></a>
2
+
3
+ [![CI][ci-shield]][ci-url]
4
+ [![npm version][npm-shield]][npm-url]
5
+ [![Bundle size][bundle-shield]][bundle-url]
6
+ [![License: MIT][license-shield]][license-url]
7
+ [![Zero dependencies][deps-shield]][deps-url]
8
+
9
+ <br />
10
+ <div align="center">
11
+ <h3 align="center">sorted-collections</h3>
12
+
13
+ <p align="center">
14
+ SortedList, SortedSet, and SortedMap for JavaScript/TypeScript
15
+ <br />
16
+ <a href="https://johansneirap.github.io/sorted-collections/"><strong>Explore the docs »</strong></a>
17
+ <br />
18
+ <br />
19
+ <a href="https://github.com/johansneirap/sorted-collections/issues/new?labels=bug&template=bug_report.md">Report Bug</a>
20
+ &middot;
21
+ <a href="https://github.com/johansneirap/sorted-collections/issues/new?labels=enhancement&template=feature_request.md">Request Feature</a>
22
+ </p>
23
+ </div>
24
+
25
+ <details>
26
+ <summary>Table of Contents</summary>
27
+ <ol>
28
+ <li>
29
+ <a href="#about-the-project">About The Project</a>
30
+ <ul>
31
+ <li><a href="#built-with">Built With</a></li>
32
+ </ul>
33
+ </li>
34
+ <li>
35
+ <a href="#getting-started">Getting Started</a>
36
+ <ul>
37
+ <li><a href="#prerequisites">Prerequisites</a></li>
38
+ <li><a href="#installation">Installation</a></li>
39
+ </ul>
40
+ </li>
41
+ <li><a href="#usage">Usage</a></li>
42
+ <li><a href="#performance">Performance</a></li>
43
+ <li><a href="#roadmap">Roadmap</a></li>
44
+ <li><a href="#contributing">Contributing</a></li>
45
+ <li><a href="#license">License</a></li>
46
+ <li><a href="#contact">Contact</a></li>
47
+ <li><a href="#acknowledgments">Acknowledgments</a></li>
48
+ </ol>
49
+ </details>
50
+
51
+ <!-- ABOUT THE PROJECT -->
52
+ ## About The Project
53
+
54
+ JavaScript/TypeScript has no built-in data structure that keeps its elements in sorted
55
+ order as you mutate it. Common patterns — leaderboards, order books, "give me everything
56
+ between X and Y" — end up re-sorting an array by hand on every insert, which is
57
+ `O(n log n)` repeated: fine for a handful of items, expensive at scale.
58
+
59
+ `sorted-collections` gives you three structures instead, with zero runtime dependencies
60
+ and a ~2 KB gzipped bundle (see the badge above for the current, live number):
61
+
62
+ * **`SortedList`** — a list that keeps insertion order sorted automatically.
63
+ * **`SortedSet`** — a sorted set with no duplicates, plus set-theory operations
64
+ (`union`, `intersection`, `difference`, `isSubsetOf`).
65
+ * **`SortedMap`** — a dictionary ordered by key.
66
+
67
+ | | `sorted-collections` | `Array` + manual sort | native `Set`/`Map` | Other npm packages in this space | Python's `sortedcontainers` |
68
+ |---|---|---|---|---|---|
69
+ | `SortedList` | ✅ | — | — | Partial coverage, low adoption | ✅ (`SortedList`) |
70
+ | `SortedSet` | ✅ | — | ✅ unordered | Partial coverage, low adoption | ✅ (`SortedSet`) |
71
+ | `SortedMap` | ✅ | — | ✅ unordered | Partial coverage, low adoption | ✅ (`SortedDict`) |
72
+ | Ordered iteration | ✅ | manual | ❌ | Varies | ✅ |
73
+ | Range queries (`irange`/`islice`) | ✅ | manual | ❌ | Varies | ✅ |
74
+ | Zero dependencies | ✅ | ✅ | ✅ | Varies | ✅ (stdlib) |
75
+
76
+ All three are backed by the same "list of lists" (bucketed array) technique Python's
77
+ [`sortedcontainers`](https://github.com/grantjenks/python-sortedcontainers) uses —
78
+ buckets of roughly `√n` sorted elements, trading a small amount of positional-access
79
+ speed for a much simpler, easier-to-audit implementation than a balanced tree. See
80
+ [`src/internal/bucket-engine.ts`](src/internal/bucket-engine.ts) for the actual
81
+ implementation, and [Performance](#performance) for what that trade-off looks like in
82
+ real numbers. The package is written in TypeScript but designed to be just as
83
+ comfortable from plain JavaScript — hence no `-ts` in the name.
84
+
85
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
86
+
87
+ ### Built With
88
+
89
+ * [![TypeScript][typescript-badge]][typescript-url]
90
+ * [![Vitest][vitest-badge]][vitest-url]
91
+ * [![Biome][biome-badge]][biome-url]
92
+
93
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
94
+
95
+ <!-- GETTING STARTED -->
96
+ ## Getting Started
97
+
98
+ ### Prerequisites
99
+
100
+ Node.js `^20.19.0` or `>=22.12.0`.
101
+
102
+ ### Installation
103
+
104
+ ```bash
105
+ npm i sorted-collections
106
+ ```
107
+
108
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
109
+
110
+ <!-- USAGE EXAMPLES -->
111
+ ## Usage
112
+
113
+ ```ts
114
+ import { SortedList, SortedSet, SortedMap } from 'sorted-collections';
115
+
116
+ const scores = new SortedList<number>();
117
+ scores.add(42);
118
+ scores.add(7);
119
+ scores.add(99);
120
+ [...scores]; // [7, 42, 99]
121
+
122
+ const tags = new SortedSet<string>(['b', 'a', 'c']);
123
+ tags.has('b'); // true
124
+
125
+ const byPrice = new SortedMap<number, string>();
126
+ byPrice.set(101.5, 'order-1');
127
+ byPrice.set(99.75, 'order-2');
128
+ [...byPrice.keys()]; // [99.75, 101.5]
129
+ ```
130
+
131
+ Range queries work the same way across all three structures:
132
+
133
+ ```ts
134
+ // Everyone scoring between 50 and 100, inclusive:
135
+ [...scores.irange(50, 100)];
136
+
137
+ // Order book: every order priced at 100 or less:
138
+ [...byPrice.irange(undefined, 100)];
139
+ ```
140
+
141
+ _Full API reference and use-case guides (leaderboards, order books, time-series) live at
142
+ [johansneirap.github.io/sorted-collections](https://johansneirap.github.io/sorted-collections/)._
143
+
144
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
145
+
146
+ <!-- PERFORMANCE -->
147
+ ## Performance
148
+
149
+ Numbers below: Node v25, single run of `npm run bench` (script in
150
+ [`benchmarks/`](benchmarks/) — reproduce locally with `npm run bench`; results vary by
151
+ machine). Ops/sec, higher is better.
152
+
153
+ | Operation | `SortedList` | `Array` (naive) |
154
+ |---|---:|---:|
155
+ | `add()`, one at a time, n=5,000 | 3,146/s | 12/s |
156
+ | `has()`, n=100,000 | 20,224/s | 67/s |
157
+
158
+ | Operation | `SortedSet` | native `Set` |
159
+ |---|---:|---:|
160
+ | `add()`, one at a time, n=5,000 | 2,092/s | 12,923/s |
161
+ | `has()`, n=100,000 | 20,121/s | 835,314/s |
162
+
163
+ | Operation | `SortedMap` | native `Map` |
164
+ |---|---:|---:|
165
+ | `set()`, one at a time, n=5,000 | 1,397/s | 7,056/s |
166
+ | `get()`, n=100,000 | 12,453/s | 834,080/s |
167
+
168
+ **Honest notes — when this library is (and isn't) the right call:**
169
+
170
+ * Native `Set`/`Map` numbers are a raw-speed reference only, not an apples-to-apples
171
+ comparison: they don't keep anything sorted, don't offer `irange`/`at`/`bisectLeft`,
172
+ and iterate in insertion order rather than sorted order. You pay for order; this is
173
+ what that cost looks like next to not paying for it.
174
+ * `add()`/`set()` vs. the naive "array + resort on every insert" pattern is only run up
175
+ to n=5,000 — that pattern is `O(n² log n)` and would take minutes at n=100,000. That
176
+ collapse *is* the problem this library exists to fix, not an oversight in the
177
+ benchmark.
178
+ * `at(index)` and full iteration are `O(√n)`, documented as such — this library
179
+ deliberately doesn't maintain the extra index a balanced tree would need for `O(log n)`
180
+ positional access, favoring a simpler implementation instead. That trade-off costs
181
+ the most on large collections doing lots of positional lookups; `has()`/`get()`/`add()`/
182
+ `set()` don't pay it.
183
+
184
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
185
+
186
+ <!-- ROADMAP -->
187
+ ## Roadmap
188
+
189
+ - [x] `SortedList`, `SortedSet`, `SortedMap` implemented, 100% test coverage
190
+ - [x] Property-based tests against naive reference implementations ([`fast-check`](https://github.com/dubzzz/fast-check))
191
+ - [x] Reproducible benchmark suite
192
+ - [x] Publish `1.0.0` to npm
193
+ - [x] Documentation site (getting started, use-case guides, API reference)
194
+
195
+ See the [open issues](https://github.com/johansneirap/sorted-collections/issues) for
196
+ proposed features and known issues.
197
+
198
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
199
+
200
+ <!-- CONTRIBUTING -->
201
+ ## Contributing
202
+
203
+ Contributions are what make the open source community such an amazing place to learn,
204
+ inspire, and create. Any contributions you make are **greatly appreciated**. See
205
+ [`CONTRIBUTING.md`](CONTRIBUTING.md) for the full guide — environment setup, what a PR
206
+ needs (tests, a changeset), and code style.
207
+
208
+ 1. Fork the Project
209
+ 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
210
+ 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
211
+ 4. Push to the Branch (`git push origin feature/AmazingFeature`)
212
+ 5. Open a Pull Request
213
+
214
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
215
+
216
+ <!-- LICENSE -->
217
+ ## License
218
+
219
+ Distributed under the MIT License. See [`LICENSE`](LICENSE) for more information.
220
+
221
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
222
+
223
+ <!-- CONTACT -->
224
+ ## Contact
225
+
226
+ Open an [issue](https://github.com/johansneirap/sorted-collections/issues) — bug
227
+ reports and feature requests both welcome.
228
+
229
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
230
+
231
+ <!-- ACKNOWLEDGMENTS -->
232
+ ## Acknowledgments
233
+
234
+ * [`sortedcontainers`](https://github.com/grantjenks/python-sortedcontainers) by Grant
235
+ Jenks — the Python library this project takes its core "list of lists" technique and
236
+ naming conventions from.
237
+ * [Best-README-Template](https://github.com/othneildrew/Best-README-Template) — the
238
+ structure this README is based on.
239
+
240
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
241
+
242
+ <!-- MARKDOWN LINKS & IMAGES -->
243
+ [ci-shield]: https://github.com/johansneirap/sorted-collections/actions/workflows/ci.yml/badge.svg
244
+ [ci-url]: https://github.com/johansneirap/sorted-collections/actions/workflows/ci.yml
245
+ [npm-shield]: https://img.shields.io/npm/v/sorted-collections.svg
246
+ [npm-url]: https://www.npmjs.com/package/sorted-collections
247
+ [bundle-shield]: https://img.shields.io/bundlephobia/minzip/sorted-collections
248
+ [bundle-url]: https://bundlephobia.com/package/sorted-collections
249
+ [license-shield]: https://img.shields.io/npm/l/sorted-collections.svg
250
+ [license-url]: https://github.com/johansneirap/sorted-collections/blob/main/LICENSE
251
+ [deps-shield]: https://img.shields.io/badge/dependencies-0-brightgreen.svg
252
+ [deps-url]: package.json
253
+ [typescript-badge]: https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white
254
+ [typescript-url]: https://www.typescriptlang.org/
255
+ [vitest-badge]: https://img.shields.io/badge/vitest-%23729B1B.svg?style=for-the-badge&logo=vitest&logoColor=white
256
+ [vitest-url]: https://vitest.dev/
257
+ [biome-badge]: https://img.shields.io/badge/biome-%2360A5FA.svg?style=for-the-badge&logo=biome&logoColor=white
258
+ [biome-url]: https://biomejs.dev/
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';function m(i,t,e,r){let n=0,o=i;for(;n<o;){let s=n+o>>>1,a=e(t(s));(r==="left"?a>=0:a>0)?o=s:n=s+1;}return n}var h=class h{constructor(t){this.buckets=[];this.count=0;this.comparator=t;}targetBucketSize(){return Math.max(h.MIN_BUCKET_SIZE,Math.ceil(Math.sqrt(this.count)))}maybeSplit(t){let e=this.buckets[t],r=this.targetBucketSize();if(e.length>r*2){let n=e.length>>>1,o=e.splice(n);this.buckets.splice(t+1,0,o);}}maybeMerge(t){let e=this.buckets[t];if(e.length===0){this.buckets.splice(t,1);return}if(this.buckets.length<=1)return;let r=this.targetBucketSize();if(e.length<r/2){let n=t>0?t-1:t+1,[o,s]=t<n?[t,n]:[n,t],a=this.buckets[o].concat(this.buckets[s]);this.buckets.splice(o,2,a),this.maybeSplit(o);}}locateBy(t,e){let r=m(this.buckets.length,a=>{let d=this.buckets[a];return d[d.length-1]},t,e),n=Math.min(r,this.buckets.length-1),o=this.buckets[n],s=m(o.length,a=>o[a],t,e);return {bucketIndex:n,localIndex:s}}locate(t,e){return this.locateBy(r=>this.comparator(r,t),e)}locatePosition(t){if(t<0||t>=this.count)return;let e=t;for(let r=0;r<this.buckets.length;r++){let n=this.buckets[r];if(e<n.length)return {bucketIndex:r,localIndex:e};e-=n.length;}throw new Error("BucketEngine: internal invariant violated (count out of sync with buckets)")}globalIndex(t,e){let r=e;for(let n=0;n<t;n++)r+=this.buckets[n].length;return r}resolveIndex(t){return t<0?this.count+t:t}*iterateRange(t,e){for(let r=t.bucketIndex;r<this.buckets.length;r++){if(e&&r>e.bucketIndex)return;let n=this.buckets[r],o=r===t.bucketIndex?t.localIndex:0,s=e&&r===e.bucketIndex?e.localIndex:n.length;for(let a=o;a<s;a++)yield n[a];}}add(t){if(this.buckets.length===0){this.buckets.push([t]),this.count+=1;return}let{bucketIndex:e,localIndex:r}=this.locate(t,"right");this.buckets[e].splice(r,0,t),this.count+=1,this.maybeSplit(e);}set(t){if(this.buckets.length===0){this.buckets.push([t]),this.count+=1;return}let{bucketIndex:e,localIndex:r}=this.locate(t,"left"),n=this.buckets[e];if(r<n.length&&this.comparator(n[r],t)===0){n[r]=t;return}n.splice(r,0,t),this.count+=1,this.maybeSplit(e);}remove(t){return this.removeBy(e=>this.comparator(e,t))}removeBy(t){if(this.buckets.length===0)return false;let{bucketIndex:e,localIndex:r}=this.locateBy(t,"left"),n=this.buckets[e];return r>=n.length||t(n[r])!==0?false:(n.splice(r,1),this.count-=1,this.maybeMerge(e),true)}discard(t){this.remove(t);}pop(t){if(this.count===0)throw new RangeError("SortedList#pop: list is empty");let e=t===void 0?this.count-1:this.resolveIndex(t),r=this.locatePosition(e);if(!r)throw new RangeError(`SortedList#pop: index ${t} is out of range`);let n=this.buckets[r.bucketIndex],[o]=n.splice(r.localIndex,1);return this.count-=1,this.maybeMerge(r.bucketIndex),o}at(t){let e=this.locatePosition(this.resolveIndex(t));if(e)return this.buckets[e.bucketIndex][e.localIndex]}indexOf(t){if(this.buckets.length===0)return -1;let{bucketIndex:e,localIndex:r}=this.locate(t,"left"),n=this.buckets[e];return r>=n.length||this.comparator(n[r],t)!==0?-1:this.globalIndex(e,r)}has(t){return this.hasBy(e=>this.comparator(e,t))}hasBy(t){return this.findBy(t)!==void 0}findBy(t){if(this.buckets.length===0)return;let{bucketIndex:e,localIndex:r}=this.locateBy(t,"left"),n=this.buckets[e];return r<n.length&&t(n[r])===0?n[r]:void 0}bisectLeft(t){if(this.buckets.length===0)return 0;let{bucketIndex:e,localIndex:r}=this.locate(t,"left");return this.globalIndex(e,r)}bisectRight(t){if(this.buckets.length===0)return 0;let{bucketIndex:e,localIndex:r}=this.locate(t,"right");return this.globalIndex(e,r)}irange(t,e,r){if(this.buckets.length===0)return this.iterateRange({bucketIndex:0,localIndex:0});let[n,o]=r?.inclusive??[true,true],s=t===void 0?{bucketIndex:0,localIndex:0}:this.locate(t,n?"left":"right"),a=e===void 0?void 0:this.locate(e,o?"right":"left");return this.iterateRange(s,a)}islice(t,e){let r=Math.max(0,t===void 0?0:this.resolveIndex(t)),n=Math.min(this.count,e===void 0?this.count:this.resolveIndex(e));if(r>=n||this.count===0)return this.iterateRange({bucketIndex:0,localIndex:0},{bucketIndex:0,localIndex:0});let o=this.locatePosition(r),s=this.locatePosition(n-1);return this.iterateRange(o,{bucketIndex:s.bucketIndex,localIndex:s.localIndex+1})}get length(){return this.count}clear(){this.buckets=[],this.count=0;}[Symbol.iterator](){return this.iterateRange({bucketIndex:0,localIndex:0})}};h.MIN_BUCKET_SIZE=32;var c=h;function f(i,t){if(typeof i=="number"&&typeof t=="number")return i-t;let e=String(i),r=String(t);return e<r?-1:e>r?1:0}var u=class i{constructor(t,...e){let n=e[0]?.comparator??f;this.engine=new c(n),t&&this.update(t);}comparatorArg(){return [{comparator:this.engine.comparator}]}add(t){this.engine.add(t);}update(t){for(let e of t)this.add(e);}remove(t){return this.engine.remove(t)}discard(t){this.engine.discard(t);}pop(t){return this.engine.pop(t)}at(t){return this.engine.at(t)}indexOf(t){return this.engine.indexOf(t)}has(t){return this.engine.has(t)}bisectLeft(t){return this.engine.bisectLeft(t)}bisectRight(t){return this.engine.bisectRight(t)}irange(t,e,r){return this.engine.irange(t,e,r)}islice(t,e){return this.engine.islice(t,e)}get length(){return this.engine.length}clear(){this.engine.clear();}clone(){return new i(this,...this.comparatorArg())}[Symbol.iterator](){return this.engine[Symbol.iterator]()}};var l=class i extends u{add(t){this.has(t)||super.add(t);}clone(){return new i(this,...this.comparatorArg())}union(t){let e=this.clone();for(let r of t)e.add(r);return e}intersection(t){let e=new i([],...this.comparatorArg());for(let r of this)t.has(r)&&e.add(r);return e}difference(t){let e=new i([],...this.comparatorArg());for(let r of this)t.has(r)||e.add(r);return e}isSubsetOf(t){for(let e of this)if(!t.has(e))return false;return true}};function p(i,t){if(typeof i=="number"&&typeof t=="number")return i-t;let e=String(i),r=String(t);return e<r?-1:e>r?1:0}function g(i){return [{comparator:i}]}var b=class{constructor(t,...e){let r=e[0];this.keyComparator=r?.comparator??p;let n=(o,s)=>this.keyComparator(o[0],s[0]);if(this.engine=new c(n),t)for(let[o,s]of t)this.set(o,s);}set(t,e){this.engine.set([t,e]);}get(t){return this.engine.findBy(e=>this.keyComparator(e[0],t))?.[1]}delete(t){return this.engine.removeBy(e=>this.keyComparator(e[0],t))}has(t){return this.engine.hasBy(e=>this.keyComparator(e[0],t))}keys(){return new l(this.keysGenerator(),...g(this.keyComparator))}*keysGenerator(){for(let[t]of this.engine)yield t;}*values(){for(let[,t]of this.engine)yield t;}entries(){return this.engine[Symbol.iterator]()}irange(t,e){let r=t===void 0?void 0:[t,void 0],n=e===void 0?void 0:[e,void 0];return this.engine.irange(r,n)}at(t){return this.engine.at(t)}get size(){return this.engine.length}clear(){this.engine.clear();}[Symbol.iterator](){return this.engine[Symbol.iterator]()}};exports.SortedList=u;exports.SortedMap=b;exports.SortedSet=l;//# sourceMappingURL=index.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/bucket-engine.ts","../src/sorted-list.ts","../src/sorted-set.ts","../src/sorted-map.ts"],"names":["bisectByCompare","length","getCandidate","compare","bias","lo","hi","mid","cmp","_BucketEngine","comparator","bucketIndex","bucket","target","right","neighborIndex","a","b","merged","i","clampedBucketIndex","localIndex","value","candidate","index","remaining","total","start","end","from","to","resolved","location","min","max","options","minInclusive","maxInclusive","resolvedStart","resolvedEnd","startLoc","endLoc","BucketEngine","defaultComparator","left","SortedList","_SortedList","iterable","SortedSet","_SortedSet","other","result","defaultKeyComparator","comparatorArgs","SortedMap","entries","opts","entryComparator","key","entry","minKey","maxKey"],"mappings":"aAWA,SAASA,CAAAA,CACPC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACQ,CACR,IAAIC,CAAAA,CAAK,CAAA,CACLC,CAAAA,CAAKL,CAAAA,CACT,KAAOI,CAAAA,CAAKC,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EAAA,CAAGA,CAAK,CAC7B,CAQA,IAAI,IAAA,EAAe,CACjB,OAAO,IAAA,CAAK,OAAO,MACrB,CAUA,OAAc,CACZ,IAAA,CAAK,MAAA,CAAO,KAAA,GACd,CAUA,CAAC,MAAA,CAAO,QAAQ,CAAA,EAA8B,CAC5C,OAAO,IAAA,CAAK,OAAO,MAAA,CAAO,QAAQ,CAAA,EACpC,CACF","file":"index.cjs","sourcesContent":["import type { Comparator } from '../types.js';\n\ntype Bias = 'left' | 'right';\n\n/**\n * Generic binary search over `length` candidates. `compare(candidate)` must\n * return the same sign a comparator would for `comparator(candidate, target)`\n * — i.e. negative if the candidate sorts before the (implicit) target.\n * Taking a closure instead of `(target, comparator)` lets callers search by\n * a bare key without constructing a throwaway full element to compare against.\n */\nfunction bisectByCompare<T>(\n length: number,\n getCandidate: (index: number) => T,\n compare: (candidate: T) => number,\n bias: Bias,\n): number {\n let lo = 0;\n let hi = length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n const cmp = compare(getCandidate(mid));\n const goLeft = bias === 'left' ? cmp >= 0 : cmp > 0;\n if (goLeft) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return lo;\n}\n\ninterface BucketLocation {\n bucketIndex: number;\n localIndex: number;\n}\n\n/**\n * Internal \"list of lists\" (sqrt-decomposition) engine shared by `SortedList`\n * and `SortedMap` — not part of the public API.\n *\n * Buckets of roughly √n sorted elements each, the same technique used by\n * Python's `sortedcontainers`. Locating a bucket by value is a binary search\n * over bucket boundaries (O(log buckets)); locating by position walks bucket\n * lengths (O(buckets)). With bucket count kept close to √n, that's O(log n)\n * and O(√n) respectively.\n *\n * `SortedMap` uses the `*By` methods directly (with a closure that compares\n * a stored `[K, V]` entry against a bare key) instead of `SortedList`'s\n * public wrapper: going through `bisectLeft` + `at` would pay for a\n * positional index (O(√n)) it doesn't need, and comparing via a search value\n * would need a throwaway `[key, undefined]` tuple and double key-unwrapping\n * per comparison instead of one.\n */\nexport class BucketEngine<T> implements Iterable<T> {\n private static readonly MIN_BUCKET_SIZE = 32;\n\n private buckets: T[][] = [];\n private count = 0;\n readonly comparator: Comparator<T>;\n\n constructor(comparator: Comparator<T>) {\n this.comparator = comparator;\n }\n\n private targetBucketSize(): number {\n return Math.max(BucketEngine.MIN_BUCKET_SIZE, Math.ceil(Math.sqrt(this.count)));\n }\n\n private maybeSplit(bucketIndex: number): void {\n const bucket = this.buckets[bucketIndex]!;\n const target = this.targetBucketSize();\n if (bucket.length > target * 2) {\n const mid = bucket.length >>> 1;\n const right = bucket.splice(mid);\n this.buckets.splice(bucketIndex + 1, 0, right);\n }\n }\n\n private maybeMerge(bucketIndex: number): void {\n const bucket = this.buckets[bucketIndex]!;\n if (bucket.length === 0) {\n this.buckets.splice(bucketIndex, 1);\n return;\n }\n if (this.buckets.length <= 1) {\n return;\n }\n const target = this.targetBucketSize();\n if (bucket.length < target / 2) {\n const neighborIndex = bucketIndex > 0 ? bucketIndex - 1 : bucketIndex + 1;\n const [a, b] =\n bucketIndex < neighborIndex ? [bucketIndex, neighborIndex] : [neighborIndex, bucketIndex];\n const merged = this.buckets[a]!.concat(this.buckets[b]!);\n this.buckets.splice(a, 2, merged);\n this.maybeSplit(a);\n }\n }\n\n /** Lookup by an arbitrary comparison closure: which (bucket, local index) does it point to? O(log n). Callers must ensure buckets is non-empty. */\n private locateBy(compare: (candidate: T) => number, bias: Bias): BucketLocation {\n const bucketIndex = bisectByCompare(\n this.buckets.length,\n (i) => {\n const bucket = this.buckets[i]!;\n return bucket[bucket.length - 1]!;\n },\n compare,\n bias,\n );\n const clampedBucketIndex = Math.min(bucketIndex, this.buckets.length - 1);\n const bucket = this.buckets[clampedBucketIndex]!;\n const localIndex = bisectByCompare(bucket.length, (i) => bucket[i]!, compare, bias);\n return { bucketIndex: clampedBucketIndex, localIndex };\n }\n\n /** Value-based lookup: which (bucket, local index) does `value` belong at? O(log n). Callers must ensure buckets is non-empty. */\n private locate(value: T, bias: Bias): BucketLocation {\n return this.locateBy((candidate) => this.comparator(candidate, value), bias);\n }\n\n /** Position-based lookup: which (bucket, local index) is global index `index` at? O(√n). */\n private locatePosition(index: number): BucketLocation | undefined {\n if (index < 0 || index >= this.count) {\n return undefined;\n }\n let remaining = index;\n for (let i = 0; i < this.buckets.length; i++) {\n const bucket = this.buckets[i]!;\n if (remaining < bucket.length) {\n return { bucketIndex: i, localIndex: remaining };\n }\n remaining -= bucket.length;\n }\n /* v8 ignore next -- unreachable unless `count` desyncs from `buckets`, which would be an internal bug */\n throw new Error('BucketEngine: internal invariant violated (count out of sync with buckets)');\n }\n\n /** Inverse of {@link locatePosition}: sums preceding bucket lengths. O(√n). */\n private globalIndex(bucketIndex: number, localIndex: number): number {\n let total = localIndex;\n for (let i = 0; i < bucketIndex; i++) {\n total += this.buckets[i]!.length;\n }\n return total;\n }\n\n private resolveIndex(index: number): number {\n return index < 0 ? this.count + index : index;\n }\n\n private *iterateRange(start: BucketLocation, end?: BucketLocation): Generator<T> {\n for (let bucketIndex = start.bucketIndex; bucketIndex < this.buckets.length; bucketIndex++) {\n if (end && bucketIndex > end.bucketIndex) {\n return;\n }\n const bucket = this.buckets[bucketIndex]!;\n const from = bucketIndex === start.bucketIndex ? start.localIndex : 0;\n const to = end && bucketIndex === end.bucketIndex ? end.localIndex : bucket.length;\n for (let i = from; i < to; i++) {\n yield bucket[i]!;\n }\n }\n }\n\n /** O(√n) amortized: locates the target bucket and splices the value in, splitting oversized buckets. */\n add(value: T): void {\n if (this.buckets.length === 0) {\n this.buckets.push([value]);\n this.count += 1;\n return;\n }\n const { bucketIndex, localIndex } = this.locate(value, 'right');\n this.buckets[bucketIndex]!.splice(localIndex, 0, value);\n this.count += 1;\n this.maybeSplit(bucketIndex);\n }\n\n /**\n * Replaces the stored element equal to `value` (by comparator) in place, or\n * inserts it if absent. O(log n) to locate; O(1) to replace in place, or\n * O(√n) amortized to insert. This is what backs `SortedMap#set` — cheaper\n * than a separate find-then-remove-then-add round trip.\n */\n set(value: T): void {\n if (this.buckets.length === 0) {\n this.buckets.push([value]);\n this.count += 1;\n return;\n }\n const { bucketIndex, localIndex } = this.locate(value, 'left');\n const bucket = this.buckets[bucketIndex]!;\n if (localIndex < bucket.length && this.comparator(bucket[localIndex]!, value) === 0) {\n bucket[localIndex] = value;\n return;\n }\n bucket.splice(localIndex, 0, value);\n this.count += 1;\n this.maybeSplit(bucketIndex);\n }\n\n remove(value: T): boolean {\n return this.removeBy((candidate) => this.comparator(candidate, value));\n }\n\n /** Same O(log n) path as {@link remove}, via an arbitrary comparison closure instead of a full value. */\n removeBy(compare: (candidate: T) => number): boolean {\n if (this.buckets.length === 0) {\n return false;\n }\n const { bucketIndex, localIndex } = this.locateBy(compare, 'left');\n const bucket = this.buckets[bucketIndex]!;\n if (localIndex >= bucket.length || compare(bucket[localIndex]!) !== 0) {\n return false;\n }\n bucket.splice(localIndex, 1);\n this.count -= 1;\n this.maybeMerge(bucketIndex);\n return true;\n }\n\n discard(value: T): void {\n this.remove(value);\n }\n\n pop(index?: number): T {\n if (this.count === 0) {\n throw new RangeError('SortedList#pop: list is empty');\n }\n const resolved = index === undefined ? this.count - 1 : this.resolveIndex(index);\n const location = this.locatePosition(resolved);\n if (!location) {\n throw new RangeError(`SortedList#pop: index ${index} is out of range`);\n }\n const bucket = this.buckets[location.bucketIndex]!;\n const [value] = bucket.splice(location.localIndex, 1);\n this.count -= 1;\n this.maybeMerge(location.bucketIndex);\n return value as T;\n }\n\n /** O(√n): walks bucket lengths to find the element at `index` (negative indices count from the end). */\n at(index: number): T | undefined {\n const location = this.locatePosition(this.resolveIndex(index));\n if (!location) {\n return undefined;\n }\n return this.buckets[location.bucketIndex]![location.localIndex];\n }\n\n indexOf(value: T): number {\n if (this.buckets.length === 0) {\n return -1;\n }\n const { bucketIndex, localIndex } = this.locate(value, 'left');\n const bucket = this.buckets[bucketIndex]!;\n if (localIndex >= bucket.length || this.comparator(bucket[localIndex]!, value) !== 0) {\n return -1;\n }\n return this.globalIndex(bucketIndex, localIndex);\n }\n\n /** O(log n): binary search for the bucket, then binary search within it. */\n has(value: T): boolean {\n return this.hasBy((candidate) => this.comparator(candidate, value));\n }\n\n /** Same O(log n) path as {@link has}, via an arbitrary comparison closure instead of a full value. */\n hasBy(compare: (candidate: T) => number): boolean {\n return this.findBy(compare) !== undefined;\n }\n\n /** Same O(log n) path as {@link has}, but returns the actual stored element instead of a boolean. */\n findBy(compare: (candidate: T) => number): T | undefined {\n if (this.buckets.length === 0) {\n return undefined;\n }\n const { bucketIndex, localIndex } = this.locateBy(compare, 'left');\n const bucket = this.buckets[bucketIndex]!;\n return localIndex < bucket.length && compare(bucket[localIndex]!) === 0\n ? bucket[localIndex]\n : undefined;\n }\n\n bisectLeft(value: T): number {\n if (this.buckets.length === 0) {\n return 0;\n }\n const { bucketIndex, localIndex } = this.locate(value, 'left');\n return this.globalIndex(bucketIndex, localIndex);\n }\n\n bisectRight(value: T): number {\n if (this.buckets.length === 0) {\n return 0;\n }\n const { bucketIndex, localIndex } = this.locate(value, 'right');\n return this.globalIndex(bucketIndex, localIndex);\n }\n\n /** O(log n) to locate both bounds by value + O(k) to iterate the k results. */\n irange(min?: T, max?: T, options?: { inclusive?: [boolean, boolean] }): IterableIterator<T> {\n if (this.buckets.length === 0) {\n return this.iterateRange({ bucketIndex: 0, localIndex: 0 });\n }\n const [minInclusive, maxInclusive] = options?.inclusive ?? [true, true];\n const start =\n min === undefined\n ? { bucketIndex: 0, localIndex: 0 }\n : this.locate(min, minInclusive ? 'left' : 'right');\n const end = max === undefined ? undefined : this.locate(max, maxInclusive ? 'right' : 'left');\n return this.iterateRange(start, end);\n }\n\n /**\n * O(√n) to locate both positional bounds + O(k) to iterate the k results.\n * (Slightly worse than the O(log n) originally targeted for this method —\n * positional lookup fundamentally needs a bucket-length walk without a\n * Fenwick index. Confirmed empirically via `npm run bench`.)\n */\n islice(start?: number, end?: number): IterableIterator<T> {\n const resolvedStart = Math.max(0, start === undefined ? 0 : this.resolveIndex(start));\n const resolvedEnd = Math.min(\n this.count,\n end === undefined ? this.count : this.resolveIndex(end),\n );\n if (resolvedStart >= resolvedEnd || this.count === 0) {\n return this.iterateRange(\n { bucketIndex: 0, localIndex: 0 },\n { bucketIndex: 0, localIndex: 0 },\n );\n }\n const startLoc = this.locatePosition(resolvedStart)!;\n const endLoc = this.locatePosition(resolvedEnd - 1)!;\n return this.iterateRange(startLoc, {\n bucketIndex: endLoc.bucketIndex,\n localIndex: endLoc.localIndex + 1,\n });\n }\n\n get length(): number {\n return this.count;\n }\n\n clear(): void {\n this.buckets = [];\n this.count = 0;\n }\n\n [Symbol.iterator](): IterableIterator<T> {\n return this.iterateRange({ bucketIndex: 0, localIndex: 0 });\n }\n}\n","import { BucketEngine } from './internal/bucket-engine.js';\nimport type { Comparator, ComparatorArg, SortedOptions } from './types.js';\n\nfunction defaultComparator<T>(a: T, b: T): number {\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n const left = String(a);\n const right = String(b);\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n\n/**\n * A list that keeps its elements in sorted order as they're inserted.\n *\n * A thin public wrapper around the internal {@link BucketEngine} — see there\n * for the actual \"list of lists\" (sqrt-decomposition) implementation and its\n * complexity notes.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([42, 7, 99]);\n * scores.add(15);\n * [...scores]; // [7, 15, 42, 99]\n * ```\n */\nexport class SortedList<T> implements Iterable<T> {\n private readonly engine: BucketEngine<T>;\n\n /**\n * @example\n * ```ts\n * new SortedList<number>(); // empty\n * new SortedList<number>([3, 1, 2]); // [1, 2, 3]\n * new SortedList<Person>([...], { comparator: (a, b) => a.age - b.age });\n * ```\n */\n constructor(iterable?: Iterable<T>, ...options: ComparatorArg<T>) {\n const opts = options[0] as SortedOptions<T> | undefined;\n const comparator = opts?.comparator ?? (defaultComparator as Comparator<T>);\n this.engine = new BucketEngine<T>(comparator);\n // Goes through `this.update` -> `this.add` (not the engine's) so that a\n // SortedSet's overridden, deduping `add` applies during construction too.\n if (iterable) {\n this.update(iterable);\n }\n }\n\n /** Safe to call from subclasses/clone: both `ComparatorArg<T>` branches accept `{ comparator }`. */\n protected comparatorArg(): ComparatorArg<T> {\n return [{ comparator: this.engine.comparator }] as unknown as ComparatorArg<T>;\n }\n\n /**\n * O(√n) amortized.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>();\n * scores.add(42);\n * scores.add(7);\n * [...scores]; // [7, 42]\n * ```\n */\n add(value: T): void {\n this.engine.add(value);\n }\n\n /**\n * Bulk-inserts every value from `iterable`, one {@link add} at a time.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([3, 1]);\n * scores.update([2, 5, 4]);\n * [...scores]; // [1, 2, 3, 4, 5]\n * ```\n */\n update(iterable: Iterable<T>): void {\n for (const value of iterable) {\n this.add(value);\n }\n }\n\n /**\n * Removes the first occurrence of `value`. Returns `false` if it wasn't present.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([1, 2, 2, 3]);\n * scores.remove(2); // true — removes one occurrence\n * scores.remove(99); // false — not present\n * ```\n */\n remove(value: T): boolean {\n return this.engine.remove(value);\n }\n\n /**\n * Like {@link remove}, but never throws (or returns anything) if `value` isn't present.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([1, 2, 3]);\n * scores.discard(99); // no-op, no error\n * ```\n */\n discard(value: T): void {\n this.engine.discard(value);\n }\n\n /**\n * Removes and returns the element at `index` (default: the last element).\n * Negative indices count from the end, same as {@link at}.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([10, 20, 30]);\n * scores.pop(); // 30 — last element\n * scores.pop(0); // 10 — first element\n * ```\n */\n pop(index?: number): T {\n return this.engine.pop(index);\n }\n\n /**\n * O(√n): walks bucket lengths to find the element at `index` (negative indices count from the end).\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([10, 20, 30]);\n * scores.at(0); // 10\n * scores.at(-1); // 30 — same as Array.prototype.at\n * scores.at(99); // undefined — out of range\n * ```\n */\n at(index: number): T | undefined {\n return this.engine.at(index);\n }\n\n /**\n * The index of the first occurrence of `value`, or `-1` if absent.\n *\n * @example\n * ```ts\n * new SortedList<number>([1, 2, 2, 3]).indexOf(2); // 1\n * new SortedList<number>([1, 2, 3]).indexOf(99); // -1\n * ```\n */\n indexOf(value: T): number {\n return this.engine.indexOf(value);\n }\n\n /**\n * O(log n): binary search for the bucket, then binary search within it.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([1, 2, 3]);\n * scores.has(2); // true\n * scores.has(99); // false\n * ```\n */\n has(value: T): boolean {\n return this.engine.has(value);\n }\n\n /**\n * The leftmost index where `value` could be inserted while keeping the list sorted.\n *\n * @example\n * ```ts\n * new SortedList<number>([1, 2, 2, 2, 3]).bisectLeft(2); // 1\n * ```\n */\n bisectLeft(value: T): number {\n return this.engine.bisectLeft(value);\n }\n\n /**\n * The rightmost index where `value` could be inserted while keeping the list sorted.\n *\n * @example\n * ```ts\n * new SortedList<number>([1, 2, 2, 2, 3]).bisectRight(2); // 4\n * ```\n */\n bisectRight(value: T): number {\n return this.engine.bisectRight(value);\n }\n\n /**\n * O(log n) to locate both bounds by value + O(k) to iterate the k results.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([1, 2, 3, 4, 5]);\n * [...scores.irange(2, 4)]; // [2, 3, 4] — inclusive by default\n * [...scores.irange(2, 4, { inclusive: [false, true] })]; // [3, 4]\n * ```\n */\n irange(min?: T, max?: T, options?: { inclusive?: [boolean, boolean] }): IterableIterator<T> {\n return this.engine.irange(min, max, options);\n }\n\n /**\n * O(√n) to locate both positional bounds + O(k) to iterate the k results.\n *\n * @example\n * ```ts\n * const scores = new SortedList<number>([10, 20, 30, 40, 50]);\n * [...scores.islice(1, 4)]; // [20, 30, 40] — like Array.prototype.slice\n * ```\n */\n islice(start?: number, end?: number): IterableIterator<T> {\n return this.engine.islice(start, end);\n }\n\n /**\n * @example\n * ```ts\n * new SortedList<number>([1, 2, 3]).length; // 3\n * ```\n */\n get length(): number {\n return this.engine.length;\n }\n\n /**\n * @example\n * ```ts\n * const scores = new SortedList<number>([1, 2, 3]);\n * scores.clear();\n * scores.length; // 0\n * ```\n */\n clear(): void {\n this.engine.clear();\n }\n\n /**\n * An independent copy — mutating the clone never affects the original.\n *\n * @example\n * ```ts\n * const original = new SortedList<number>([1, 2, 3]);\n * const copy = original.clone();\n * copy.add(4);\n * original.length; // 3\n * copy.length; // 4\n * ```\n */\n clone(): SortedList<T> {\n return new SortedList<T>(this, ...this.comparatorArg());\n }\n\n /**\n * @example\n * ```ts\n * const scores = new SortedList<number>([3, 1, 2]);\n * for (const value of scores) console.log(value); // 1, 2, 3\n * ```\n */\n [Symbol.iterator](): IterableIterator<T> {\n return this.engine[Symbol.iterator]();\n }\n}\n","import { SortedList } from './sorted-list.js';\n\n/**\n * Like {@link SortedList}, but rejects duplicates (compared via the\n * comparator, not reference identity). Adds set-theory operations.\n *\n * Reuses `SortedList`'s bucket structure entirely: the only behavioral\n * difference is that `add` is a no-op for values already present.\n *\n * @example\n * ```ts\n * const tags = new SortedSet<string>(['b', 'a', 'c', 'a']);\n * [...tags]; // ['a', 'b', 'c'] — the duplicate 'a' was dropped\n * ```\n */\nexport class SortedSet<T> extends SortedList<T> {\n /**\n * O(log n) `has` check + O(√n) amortized insert if the value is new.\n *\n * @example\n * ```ts\n * const tags = new SortedSet<string>(['a']);\n * tags.add('a'); // no-op, already present\n * tags.length; // 1\n * ```\n */\n override add(value: T): void {\n if (!this.has(value)) {\n super.add(value);\n }\n }\n\n /**\n * @example\n * ```ts\n * const original = new SortedSet<number>([1, 2, 3]);\n * const copy = original.clone();\n * copy.add(4);\n * original.length; // 3\n * ```\n */\n override clone(): SortedSet<T> {\n return new SortedSet<T>(this, ...this.comparatorArg());\n }\n\n /**\n * O(m log n + m) for a set of size m being merged in.\n *\n * @example\n * ```ts\n * const a = new SortedSet<number>([1, 2, 3]);\n * const b = new SortedSet<number>([3, 4]);\n * [...a.union(b)]; // [1, 2, 3, 4]\n * ```\n */\n union(other: SortedSet<T>): SortedSet<T> {\n const result = this.clone();\n for (const value of other) {\n result.add(value);\n }\n return result;\n }\n\n /**\n * @example\n * ```ts\n * const a = new SortedSet<number>([1, 2, 3]);\n * const b = new SortedSet<number>([2, 3, 4]);\n * [...a.intersection(b)]; // [2, 3]\n * ```\n */\n intersection(other: SortedSet<T>): SortedSet<T> {\n const result = new SortedSet<T>([], ...this.comparatorArg());\n for (const value of this) {\n if (other.has(value)) {\n result.add(value);\n }\n }\n return result;\n }\n\n /**\n * @example\n * ```ts\n * const a = new SortedSet<number>([1, 2, 3]);\n * const b = new SortedSet<number>([2, 3]);\n * [...a.difference(b)]; // [1] — in a, not in b\n * ```\n */\n difference(other: SortedSet<T>): SortedSet<T> {\n const result = new SortedSet<T>([], ...this.comparatorArg());\n for (const value of this) {\n if (!other.has(value)) {\n result.add(value);\n }\n }\n return result;\n }\n\n /**\n * @example\n * ```ts\n * new SortedSet<number>([2, 3]).isSubsetOf(new SortedSet<number>([1, 2, 3, 4])); // true\n * new SortedSet<number>([1, 5]).isSubsetOf(new SortedSet<number>([1, 2, 3])); // false\n * ```\n */\n isSubsetOf(other: SortedSet<T>): boolean {\n for (const value of this) {\n if (!other.has(value)) {\n return false;\n }\n }\n return true;\n }\n}\n","import { BucketEngine } from './internal/bucket-engine.js';\nimport { SortedSet } from './sorted-set.js';\nimport type { Comparator, ComparatorArg, SortedOptions } from './types.js';\n\nfunction defaultKeyComparator<K>(a: K, b: K): number {\n if (typeof a === 'number' && typeof b === 'number') {\n return a - b;\n }\n const left = String(a);\n const right = String(b);\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n\nfunction comparatorArgs<T>(comparator: Comparator<T>): ComparatorArg<T> {\n return [{ comparator }] as unknown as ComparatorArg<T>;\n}\n\n/**\n * A dictionary ordered by key.\n *\n * Uses the internal {@link BucketEngine} directly (on `[K, V]` tuples, with a\n * comparator that only looks at the key) rather than composing over\n * `SortedList`'s public API. Two reasons: `set` needs the engine's O(log n)\n * in-place replace-or-insert (`SortedList#bisectLeft` + `#at` would pay for a\n * positional index it doesn't need), and `get`/`has`/`delete` use the `*By`\n * lookup methods with a closure over the bare key — that compares the key\n * only once per candidate (not twice, since the search side needs no\n * `entry[0]` unwrapping) and avoids allocating a throwaway `[key, undefined]`\n * search tuple per call.\n *\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[101.5, 'order-1'], [99.75, 'order-2']]);\n * [...byPrice.keys()]; // [99.75, 101.5]\n * ```\n */\nexport class SortedMap<K, V> implements Iterable<[K, V]> {\n private readonly engine: BucketEngine<[K, V]>;\n private readonly keyComparator: Comparator<K>;\n\n /**\n * @example\n * ```ts\n * new SortedMap<number, string>(); // empty\n * new SortedMap<number, string>([[2, 'b'], [1, 'a']]); // ordered by key: 1, 2\n * ```\n */\n constructor(entries?: Iterable<[K, V]>, ...options: ComparatorArg<K>) {\n const opts = options[0] as SortedOptions<K> | undefined;\n this.keyComparator = opts?.comparator ?? (defaultKeyComparator as Comparator<K>);\n const entryComparator: Comparator<[K, V]> = (a, b) => this.keyComparator(a[0], b[0]);\n this.engine = new BucketEngine<[K, V]>(entryComparator);\n if (entries) {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n }\n\n /**\n * O(log n) to locate + O(1) to replace in place, or O(√n) amortized to insert.\n *\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>();\n * byPrice.set(101.5, 'order-1');\n * byPrice.set(101.5, 'order-1-updated'); // overwrites, doesn't grow size\n * ```\n */\n set(key: K, value: V): void {\n this.engine.set([key, value]);\n }\n\n /**\n * O(log n): binary search for the bucket, then binary search within it.\n *\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[101.5, 'order-1']]);\n * byPrice.get(101.5); // 'order-1'\n * byPrice.get(1); // undefined\n * ```\n */\n get(key: K): V | undefined {\n return this.engine.findBy((entry) => this.keyComparator(entry[0], key))?.[1];\n }\n\n /**\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[101.5, 'order-1']]);\n * byPrice.delete(101.5); // true\n * byPrice.delete(101.5); // false — already gone\n * ```\n */\n delete(key: K): boolean {\n return this.engine.removeBy((entry) => this.keyComparator(entry[0], key));\n }\n\n /**\n * @example\n * ```ts\n * new SortedMap<number, string>([[1, 'a']]).has(1); // true\n * ```\n */\n has(key: K): boolean {\n return this.engine.hasBy((entry) => this.keyComparator(entry[0], key));\n }\n\n /**\n * A snapshot `SortedSet` of the current keys — not a live view.\n *\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[2, 'b'], [1, 'a']]);\n * [...byPrice.keys()]; // [1, 2]\n * ```\n */\n keys(): SortedSet<K> {\n return new SortedSet<K>(this.keysGenerator(), ...comparatorArgs(this.keyComparator));\n }\n\n private *keysGenerator(): Generator<K> {\n for (const [key] of this.engine) {\n yield key;\n }\n }\n\n /**\n * @example\n * ```ts\n * [...new SortedMap<number, string>([[2, 'b'], [1, 'a']]).values()]; // ['a', 'b']\n * ```\n */\n *values(): IterableIterator<V> {\n for (const [, value] of this.engine) {\n yield value;\n }\n }\n\n /**\n * @example\n * ```ts\n * [...new SortedMap<number, string>([[2, 'b'], [1, 'a']]).entries()]; // [[1, 'a'], [2, 'b']]\n * ```\n */\n entries(): IterableIterator<[K, V]> {\n return this.engine[Symbol.iterator]();\n }\n\n /**\n * Iterates `[key, value]` pairs with keys in `[minKey, maxKey]`.\n *\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[95, 'a'], [100, 'b'], [105, 'c']]);\n * [...byPrice.irange(95, 100)]; // [[95, 'a'], [100, 'b']]\n * ```\n */\n irange(minKey?: K, maxKey?: K): IterableIterator<[K, V]> {\n const min = minKey === undefined ? undefined : ([minKey, undefined as unknown as V] as [K, V]);\n const max = maxKey === undefined ? undefined : ([maxKey, undefined as unknown as V] as [K, V]);\n return this.engine.irange(min, max);\n }\n\n /**\n * O(√n). Entry at ordinal position `index` in key order.\n *\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[2, 'b'], [1, 'a']]);\n * byPrice.at(0); // [1, 'a']\n * ```\n */\n at(index: number): [K, V] | undefined {\n return this.engine.at(index);\n }\n\n /**\n * @example\n * ```ts\n * new SortedMap<number, string>([[1, 'a'], [2, 'b']]).size; // 2\n * ```\n */\n get size(): number {\n return this.engine.length;\n }\n\n /**\n * @example\n * ```ts\n * const byPrice = new SortedMap<number, string>([[1, 'a']]);\n * byPrice.clear();\n * byPrice.size; // 0\n * ```\n */\n clear(): void {\n this.engine.clear();\n }\n\n /**\n * @example\n * ```ts\n * for (const [key, value] of new SortedMap([[2, 'b'], [1, 'a']])) {\n * console.log(key, value); // 1 'a', then 2 'b'\n * }\n * ```\n */\n [Symbol.iterator](): IterableIterator<[K, V]> {\n return this.engine[Symbol.iterator]();\n }\n}\n"]}