@streetsidesoftware/auto-resolve-map 0.0.1-alpha.0 → 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.
Files changed (2) hide show
  1. package/README.md +163 -60
  2. package/package.json +7 -6
package/README.md CHANGED
@@ -1,10 +1,33 @@
1
1
  # @streetsidesoftware/auto-resolve-map
2
2
 
3
- Maps that compute and store a missing value, including maps that don't keep their values alive, and a function that
4
- does the same for a map you already have.
3
+ Lazy value resolution, `getOrInsert` / `getOrInsertComputed` collections, weak-value maps, and cache instrumentation for
4
+ TypeScript and JavaScript.
5
5
 
6
- Node.js 22 and 24 don't have `getOrInsert` and `getOrInsertComputed` on `Map` and `WeakMap`. The classes in this package
7
- have them on every supported version.
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.
8
31
 
9
32
  ## Install
10
33
 
@@ -12,103 +35,185 @@ have them on every supported version.
12
35
  npm install @streetsidesoftware/auto-resolve-map
13
36
  ```
14
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
+
15
54
  ## Usage
16
55
 
17
- ### A map you already have
56
+ ### `autoResolve(map, key, callback)`
18
57
 
19
- Use `autoResolve` with any object that has `get`, `has` and `set`, such as a `Map` or a `WeakMap`:
58
+ Resolves and stores a value in any existing `Map`, `WeakMap`, or custom map-like object with `get`, `has` and `set`.
20
59
 
21
60
  ```ts
22
61
  import { autoResolve } from '@streetsidesoftware/auto-resolve-map';
23
62
 
24
63
  const lengths = new Map<string, number>();
25
64
 
26
- autoResolve(lengths, 'apple', (key) => key.length); // 5, computed and stored
27
- autoResolve(lengths, 'apple', (key) => key.length); // 5, from the map
28
- ```
65
+ function measure(word: string): number {
66
+ console.log(`Measuring ${word}`);
67
+ return word.length;
68
+ }
29
69
 
30
- A stored `undefined` counts as a value. Nothing is stored when the callback throws.
70
+ autoResolve(lengths, 'apple', measure); // 5 (logs "Measuring apple")
71
+ autoResolve(lengths, 'apple', measure); // 5 (from the map)
72
+ ```
31
73
 
32
- ### A new map
74
+ **Semantics:**
33
75
 
34
- Pick a class by what it should keep alive:
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.
35
78
 
36
- | Class | Keeps its keys alive | Keeps its values alive | Use it as |
37
- | -------------------- | -------------------- | ---------------------------- | --------- |
38
- | `AutoResolveMap` | Yes | Yes | `Map` |
39
- | `AutoResolveWeakMap` | No | As long as the key is in use | `WeakMap` |
40
- | `StrongWeakMap` | Yes | No | `Map` |
41
- | `WeakWeakMap` | No | No | `WeakMap` |
79
+ ### `AutoResolveMap`
42
80
 
43
- Each has all the methods of the built-in it's used as, `getOrInsert` and `getOrInsertComputed` included. The two with
44
- weak keys also have `clear`.
81
+ A standard `Map` extended with `getOrInsert(key, value)` and `getOrInsertComputed(key, callback)`.
45
82
 
46
83
  ```ts
47
84
  import { AutoResolveMap } from '@streetsidesoftware/auto-resolve-map';
48
85
 
49
- const words = new AutoResolveMap<string, string[]>();
86
+ const byLetter = new AutoResolveMap<string, string[]>();
50
87
 
51
- words.getOrInsert('a', []).push('apple');
52
- words.getOrInsert('a', []).push('avocado');
53
- words.getOrInsertComputed('b', loadWords);
88
+ for (const word of ['apple', 'banana', 'avocado']) {
89
+ byLetter.getOrInsertComputed(word.charAt(0), () => []).push(word);
90
+ }
54
91
 
55
- words.get('a'); // ['apple', 'avocado']
56
- words.get('b'); // The result of `loadWords('b')`
92
+ byLetter.get('a'); // ['apple', 'avocado']
93
+ byLetter.get('b'); // ['banana']
57
94
  ```
58
95
 
59
- ### Values that can be released
96
+ ### `AutoResolveWeakMap`
60
97
 
61
- Use `StrongWeakMap` or `WeakWeakMap` to share a value for as long as something uses it, and to let it go after
62
- that:
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.
63
127
 
64
128
  ```ts
65
129
  import { StrongWeakMap } from '@streetsidesoftware/auto-resolve-map';
66
130
 
131
+ interface Dictionary {
132
+ language: string;
133
+ words: Set<string>;
134
+ }
135
+
67
136
  const dictionaries = new StrongWeakMap<string, Dictionary>();
68
137
 
69
- const a = dictionaries.getOrInsertComputed('colors', loadDictionary);
70
- const b = dictionaries.getOrInsertComputed('colors', loadDictionary); // The same dictionary as `a`.
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
71
147
  ```
72
148
 
73
- Once nothing else uses a value, it can be garbage collected at any time:
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`
74
163
 
75
- - After that, `get` and `has` act as if its key had never been there.
76
- - Looping over the entries or values of a `StrongWeakMap` skips it.
77
- - `StrongWeakMap` removes the key itself some time later. Until then, `size` and `keys()` include it.
78
- - Any look at a value, `has` included, keeps it alive until the current turn of the event loop ends.
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.
79
166
 
80
- Each entry of a `StrongWeakMap` has a fixed cost on top of a normal map's, whatever the size of its value. It suits a
81
- small number of large objects, such as dictionaries, and not many small ones.
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);
82
182
 
83
- ### Caches with stats
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
84
190
 
85
- Each class has a version that counts how it's used: `AutoResolveCache`, `AutoResolveWeakCache`, `StrongWeakCache` and
86
- `WeakWeakCache`.
191
+ Each `*Cache` class extends its map class, and tracks lookups and mutations.
87
192
 
88
193
  ```ts
89
194
  import { AutoResolveCache } from '@streetsidesoftware/auto-resolve-map';
90
195
 
91
- const cache = new AutoResolveCache<string, number>();
196
+ const squares = new AutoResolveCache<number, number>();
92
197
 
93
- cache.getOrInsertComputed('apple', (key) => key.length);
94
- cache.getOrInsertComputed('apple', (key) => key.length);
198
+ for (const n of [1, 2, 1, 2, 1]) {
199
+ squares.getOrInsertComputed(n, () => n * n);
200
+ }
95
201
 
96
- cache.stats(); // { hits: 1, misses: 1, resolved: 1, sets: 0, deletes: 0, clears: 0 }
202
+ squares.stats(); // { hits: 3, misses: 2, resolved: 2, sets: 0, deletes: 0, clears: 0 }
97
203
  ```
98
204
 
99
- | Count | Goes up when |
100
- | ---------- | ----------------------------------------------- |
101
- | `hits` | A lookup finds a value |
102
- | `misses` | A lookup finds none |
103
- | `resolved` | A value a callback computed is stored |
104
- | `sets` | A value is stored by `set`, or by `getOrInsert` |
105
- | `deletes` | `delete` is called |
106
- | `clears` | `clear` is called |
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`. |
107
213
 
108
- A lookup is `get`, `getOrInsert` or `getOrInsertComputed`. Calling `has` doesn't count, and neither do the entries a cache
109
- starts with.
110
-
111
- To start counting again, call `resetStats()`. It leaves the entries alone, as `clear()` leaves the earlier counts alone.
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.
112
217
 
113
218
  ## Requirements
114
219
 
@@ -134,9 +239,7 @@ If our tools save you time, please consider supporting their development.
134
239
 
135
240
  Please show your support through one of the following sites:
136
241
 
137
- <p align="left">
138
- <a href="https://github.com/sponsors/streetsidesoftware" title="GitHub Sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://streetsidesoftware.com/img/sponsor/github-sponsor-dark.png" /><img alt="GitHub Sponsor" src="https://streetsidesoftware.com/img/sponsor/github-sponsor.png" width="180" /></picture></a> &nbsp; <a href="https://thanks.dev/u/gh/streetsidesoftware" title="thanks.dev"><picture><source media="(prefers-color-scheme: dark)" srcset="https://streetsidesoftware.com/img/sponsor/thanks-dev-dark.png" /><img alt="thanks.dev" src="https://streetsidesoftware.com/img/sponsor/thanks-dev.png" width="180" /></picture></a> &nbsp; <a href="https://opencollective.com/cspell" title="Open Collective"><picture><source media="(prefers-color-scheme: dark)" srcset="https://streetsidesoftware.com/img/sponsor/open-collective-dark.png" /><img alt="Open Collective" src="https://streetsidesoftware.com/img/sponsor/open-collective.png" width="180" /></picture></a> &nbsp; <a href="https://streetsidesoftware.com/sponsor/" title="Street Side Software"><picture><source media="(prefers-color-scheme: dark)" srcset="https://streetsidesoftware.com/img/sponsor/cspell-dark.png" /><img alt="CSpell" src="https://streetsidesoftware.com/img/sponsor/cspell.png" width="180" /></picture></a>
139
- </p>
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/)
140
243
 
141
244
  <!--- @@inject-end: ../../static/sponsor.md --->
142
245
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@streetsidesoftware/auto-resolve-map",
3
- "version": "0.0.1-alpha.0",
3
+ "version": "1.0.0",
4
4
  "description": "Maps that compute and store a missing value, with strong or weak keys and values",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,13 +32,14 @@
32
32
  "dist",
33
33
  "!dist/**/*.map"
34
34
  ],
35
- "engines": {
36
- "node": ">=22.18.0"
37
- },
38
35
  "scripts": {
39
36
  "build": "tsdown",
40
37
  "clean": "shx rm -rf dist coverage",
41
38
  "test": "node --test \"src/**/*.test.ts\"",
42
39
  "typecheck": "tsc --noEmit"
43
- }
44
- }
40
+ },
41
+ "engines": {
42
+ "node": ">=22.18.0"
43
+ },
44
+ "gitHead": "20d74a14d5da2a28211873c5e4f48803f6d4fb2e"
45
+ }