@streetsidesoftware/auto-resolve-map 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Street Side Software
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 CHANGED
@@ -1,3 +1,258 @@
1
- # Temporary Holding Version
1
+ # @streetsidesoftware/auto-resolve-map
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lazy value resolution, `getOrInsert` / `getOrInsertComputed` collections, weak-value maps, and cache instrumentation for
4
+ TypeScript and JavaScript.
5
+
6
+ ## Why?
7
+
8
+ Lazily populating a `Map` or `WeakMap` requires boilerplate, and checking only the result of `get` breaks when
9
+ `undefined` is a valid value:
10
+
11
+ ```ts
12
+ let size = sizes.get(name);
13
+ if (size === undefined && !sizes.has(name)) {
14
+ size = measure(name);
15
+ sizes.set(name, size);
16
+ }
17
+ ```
18
+
19
+ The `autoResolve` function reduces this to a single, `undefined`-safe call:
20
+
21
+ ```ts
22
+ const size = autoResolve(sizes, name, measure);
23
+ ```
24
+
25
+ This package also provides:
26
+
27
+ - Map classes with `getOrInsert` and `getOrInsertComputed`, as in the
28
+ [TC39 upsert proposal](https://github.com/tc39/proposal-upsert), on every supported Node.js version.
29
+ - Maps with `WeakRef` values, for memory-sensitive caching or object canonicalization.
30
+ - Instrumented `*Cache` variants, for measuring hits and misses.
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ npm install @streetsidesoftware/auto-resolve-map
36
+ ```
37
+
38
+ ## Overview
39
+
40
+ | Export | Keys | Values | Description |
41
+ | ---------------------- | ------ | ------ | ---------------------------------------------------------------------------- |
42
+ | `autoResolve` | Any | Any | Function for any map-like object (`get`, `has`, `set`). |
43
+ | `AutoResolveMap` | Strong | Strong | `Map` subclass with `getOrInsert` and `getOrInsertComputed`. |
44
+ | `AutoResolveWeakMap` | Weak | Strong | `WeakMap` interface with `getOrInsert`, `getOrInsertComputed` and `clear`. |
45
+ | `StrongWeakMap` | Strong | Weak | `Map` interface with `WeakRef` values. Keys of collected values are removed. |
46
+ | `WeakWeakMap` | Weak | Weak | `WeakMap` interface with `WeakRef` values and `clear`. |
47
+ | `AutoResolveCache` | Strong | Strong | `AutoResolveMap` with lookup and mutation statistics. |
48
+ | `AutoResolveWeakCache` | Weak | Strong | `AutoResolveWeakMap` with lookup and mutation statistics. |
49
+ | `StrongWeakCache` | Strong | Weak | `StrongWeakMap` with lookup and mutation statistics. |
50
+ | `WeakWeakCache` | Weak | Weak | `WeakWeakMap` with lookup and mutation statistics. |
51
+
52
+ All the map classes have `getOrInsert` and `getOrInsertComputed`, with the same semantics as `autoResolve`.
53
+
54
+ ## Usage
55
+
56
+ ### `autoResolve(map, key, callback)`
57
+
58
+ Resolves and stores a value in any existing `Map`, `WeakMap`, or custom map-like object with `get`, `has` and `set`.
59
+
60
+ ```ts
61
+ import { autoResolve } from '@streetsidesoftware/auto-resolve-map';
62
+
63
+ const lengths = new Map<string, number>();
64
+
65
+ function measure(word: string): number {
66
+ console.log(`Measuring ${word}`);
67
+ return word.length;
68
+ }
69
+
70
+ autoResolve(lengths, 'apple', measure); // 5 (logs "Measuring apple")
71
+ autoResolve(lengths, 'apple', measure); // 5 (from the map)
72
+ ```
73
+
74
+ **Semantics:**
75
+
76
+ - Checks `has(key)` when `get(key)` returns `undefined`, so a stored `undefined` counts as a value.
77
+ - If `callback(key)` throws, nothing is stored and the error propagates.
78
+
79
+ ### `AutoResolveMap`
80
+
81
+ A standard `Map` extended with `getOrInsert(key, value)` and `getOrInsertComputed(key, callback)`.
82
+
83
+ ```ts
84
+ import { AutoResolveMap } from '@streetsidesoftware/auto-resolve-map';
85
+
86
+ const byLetter = new AutoResolveMap<string, string[]>();
87
+
88
+ for (const word of ['apple', 'banana', 'avocado']) {
89
+ byLetter.getOrInsertComputed(word.charAt(0), () => []).push(word);
90
+ }
91
+
92
+ byLetter.get('a'); // ['apple', 'avocado']
93
+ byLetter.get('b'); // ['banana']
94
+ ```
95
+
96
+ ### `AutoResolveWeakMap`
97
+
98
+ A `WeakMap`-compatible collection with `getOrInsert`, `getOrInsertComputed` and `clear`. It associates derived data with
99
+ an object without preventing garbage collection of that object.
100
+
101
+ ```ts
102
+ import { AutoResolveWeakMap } from '@streetsidesoftware/auto-resolve-map';
103
+
104
+ interface Settings {
105
+ words: string[];
106
+ }
107
+
108
+ const lookups = new AutoResolveWeakMap<Settings, Set<string>>();
109
+
110
+ function hasWord(settings: Settings, word: string): boolean {
111
+ const lookup = lookups.getOrInsertComputed(settings, () => new Set(settings.words));
112
+ return lookup.has(word);
113
+ }
114
+
115
+ const settings: Settings = { words: ['apple', 'banana'] };
116
+
117
+ hasWord(settings, 'apple'); // true (builds the Set)
118
+ hasWord(settings, 'cherry'); // false (reuses the Set)
119
+
120
+ lookups.clear(); // Releases every Set, even when its Settings object is still in use.
121
+ ```
122
+
123
+ ### `StrongWeakMap`
124
+
125
+ A `Map`-compatible collection with strong keys and weak values, backed by `WeakRef` and `FinalizationRegistry`. It caches
126
+ large objects, or canonicalizes instances by key, while allowing unused values to be garbage-collected.
127
+
128
+ ```ts
129
+ import { StrongWeakMap } from '@streetsidesoftware/auto-resolve-map';
130
+
131
+ interface Dictionary {
132
+ language: string;
133
+ words: Set<string>;
134
+ }
135
+
136
+ const dictionaries = new StrongWeakMap<string, Dictionary>();
137
+
138
+ function loadDictionary(language: string): Dictionary {
139
+ console.log(`Loading ${language}`);
140
+ return { language, words: new Set(['apple', 'banana']) };
141
+ }
142
+
143
+ const first = dictionaries.getOrInsertComputed('en', loadDictionary); // Logs "Loading en"
144
+ const second = dictionaries.getOrInsertComputed('en', loadDictionary);
145
+
146
+ first === second; // true
147
+ ```
148
+
149
+ **Garbage collection and memory semantics:**
150
+
151
+ - **Object values:** Values must be objects. Store the resolved object, not a promise for it. The promise can be
152
+ collected while its result is still in use.
153
+ - **Caller retention:** The map doesn't hold strong references to values. Callers must retain a reference for as long as
154
+ they need the value.
155
+ - **Lifetime:** Any lookup, including `has`, and iterating over the values or entries keep a value alive until the end of
156
+ the current turn of the event loop.
157
+ - **Key cleanup:** Once a value is collected, lookups and iteration over the values or entries treat the entry as absent.
158
+ The `FinalizationRegistry` removes the key some time later. Until then, `size` and `keys()` include it.
159
+ - **Per-entry overhead:** Each entry allocates a `WeakRef` and is registered with a `FinalizationRegistry`. For many small
160
+ objects, prefer `AutoResolveMap`.
161
+
162
+ ### `WeakWeakMap`
163
+
164
+ A `WeakMap`-compatible collection with weak keys and weak values, and `clear`. Unlike with `AutoResolveWeakMap`, a value
165
+ can be garbage-collected while its key is still alive.
166
+
167
+ ```ts
168
+ import { WeakWeakMap } from '@streetsidesoftware/auto-resolve-map';
169
+
170
+ interface TextFile {
171
+ text: string;
172
+ }
173
+
174
+ const lines = new WeakWeakMap<TextFile, string[]>();
175
+
176
+ function getLines(file: TextFile): string[] {
177
+ return lines.getOrInsertComputed(file, () => file.text.split('\n'));
178
+ }
179
+
180
+ const file: TextFile = { text: 'one\ntwo' };
181
+ const current = getLines(file);
182
+
183
+ getLines(file) === current; // true while `current` is strongly referenced
184
+ ```
185
+
186
+ Object values, caller retention and lifetime are the same as for `StrongWeakMap`. There is no `FinalizationRegistry`: the
187
+ empty `WeakRef` of a collected value stays until the entry is replaced or removed, or its key is collected.
188
+
189
+ ### Cache instrumentation
190
+
191
+ Each `*Cache` class extends its map class, and tracks lookups and mutations.
192
+
193
+ ```ts
194
+ import { AutoResolveCache } from '@streetsidesoftware/auto-resolve-map';
195
+
196
+ const squares = new AutoResolveCache<number, number>();
197
+
198
+ for (const n of [1, 2, 1, 2, 1]) {
199
+ squares.getOrInsertComputed(n, () => n * n);
200
+ }
201
+
202
+ squares.stats(); // { hits: 3, misses: 2, resolved: 2, sets: 0, deletes: 0, clears: 0 }
203
+ ```
204
+
205
+ | Metric | Description |
206
+ | ---------- | ------------------------------------------------------------------------- |
207
+ | `hits` | Lookups (`get`, `getOrInsert`, `getOrInsertComputed`) that found a value. |
208
+ | `misses` | Lookups that found no value. A collected value is a miss. |
209
+ | `resolved` | Values computed by `getOrInsertComputed` and stored. |
210
+ | `sets` | Values stored by `set` or `getOrInsert`. |
211
+ | `deletes` | Calls to `delete`. |
212
+ | `clears` | Calls to `clear`. |
213
+
214
+ - Calls to `has` and entries passed to the constructor aren't counted.
215
+ - Calling `resetStats()` sets all counters to 0 and keeps the entries.
216
+ - Calling `clear()` removes all entries and keeps the other counters.
217
+
218
+ ## Requirements
219
+
220
+ <!--- @@inject: ../../static/requirements.md#values-file=:package.json --->
221
+
222
+ Requires Node.js >=22.18.0. ESM only.
223
+
224
+ <!--- @@inject-end: ../../static/requirements.md#values-file=:package.json --->
225
+
226
+ ## License
227
+
228
+ <!--- @@inject: ../../static/licenseTpl.md#values-file=:package.json --->
229
+
230
+ MIT
231
+
232
+ <!--- @@inject-end: ../../static/licenseTpl.md#values-file=:package.json --->
233
+
234
+ ## Support Future Development
235
+
236
+ <!--- @@inject: ../../static/sponsor.md --->
237
+
238
+ If our tools save you time, please consider supporting their development.
239
+
240
+ Please show your support through one of the following sites:
241
+
242
+ [![GitHub Sponsor](https://streetsidesoftware.com/img/sponsor/github-sponsor-176px.png)](https://github.com/sponsors/streetsidesoftware) [![thanks.dev](https://streetsidesoftware.com/img/sponsor/thanks-dev-176px.png)](https://thanks.dev/u/gh/streetsidesoftware) [![Open Collective](https://streetsidesoftware.com/img/sponsor/open-collective-176px.png)](https://opencollective.com/cspell) [![CSpell](https://streetsidesoftware.com/img/sponsor/cspell-176px.png)](https://streetsidesoftware.com/sponsor/)
243
+
244
+ <!--- @@inject-end: ../../static/sponsor.md --->
245
+
246
+ <!--- @@inject: ../../static/footer.md --->
247
+
248
+ <br/>
249
+
250
+ ---
251
+
252
+ <p align="center">
253
+ Brought to you by <a href="https://streetsidesoftware.com" title="Street Side Software">
254
+ <img width="16" alt="Street Side Software Logo" src="https://i.imgur.com/CyduuVY.png" /> Street Side Software
255
+ </a>
256
+ </p>
257
+
258
+ <!--- @@inject-end: ../../static/footer.md --->