@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.
- package/README.md +163 -60
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -1,10 +1,33 @@
|
|
|
1
1
|
# @streetsidesoftware/auto-resolve-map
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
Lazy value resolution, `getOrInsert` / `getOrInsertComputed` collections, weak-value maps, and cache instrumentation for
|
|
4
|
+
TypeScript and JavaScript.
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
###
|
|
56
|
+
### `autoResolve(map, key, callback)`
|
|
18
57
|
|
|
19
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
65
|
+
function measure(word: string): number {
|
|
66
|
+
console.log(`Measuring ${word}`);
|
|
67
|
+
return word.length;
|
|
68
|
+
}
|
|
29
69
|
|
|
30
|
-
|
|
70
|
+
autoResolve(lengths, 'apple', measure); // 5 (logs "Measuring apple")
|
|
71
|
+
autoResolve(lengths, 'apple', measure); // 5 (from the map)
|
|
72
|
+
```
|
|
31
73
|
|
|
32
|
-
|
|
74
|
+
**Semantics:**
|
|
33
75
|
|
|
34
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
86
|
+
const byLetter = new AutoResolveMap<string, string[]>();
|
|
50
87
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
88
|
+
for (const word of ['apple', 'banana', 'avocado']) {
|
|
89
|
+
byLetter.getOrInsertComputed(word.charAt(0), () => []).push(word);
|
|
90
|
+
}
|
|
54
91
|
|
|
55
|
-
|
|
56
|
-
|
|
92
|
+
byLetter.get('a'); // ['apple', 'avocado']
|
|
93
|
+
byLetter.get('b'); // ['banana']
|
|
57
94
|
```
|
|
58
95
|
|
|
59
|
-
###
|
|
96
|
+
### `AutoResolveWeakMap`
|
|
60
97
|
|
|
61
|
-
|
|
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
|
-
|
|
70
|
-
|
|
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
|
-
|
|
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
|
-
|
|
76
|
-
|
|
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
|
-
|
|
81
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
196
|
+
const squares = new AutoResolveCache<number, number>();
|
|
92
197
|
|
|
93
|
-
|
|
94
|
-
|
|
198
|
+
for (const n of [1, 2, 1, 2, 1]) {
|
|
199
|
+
squares.getOrInsertComputed(n, () => n * n);
|
|
200
|
+
}
|
|
95
201
|
|
|
96
|
-
|
|
202
|
+
squares.stats(); // { hits: 3, misses: 2, resolved: 2, sets: 0, deletes: 0, clears: 0 }
|
|
97
203
|
```
|
|
98
204
|
|
|
99
|
-
|
|
|
100
|
-
| ---------- |
|
|
101
|
-
| `hits` |
|
|
102
|
-
| `misses` | A
|
|
103
|
-
| `resolved` |
|
|
104
|
-
| `sets` |
|
|
105
|
-
| `deletes` | `delete
|
|
106
|
-
| `clears` | `clear
|
|
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
|
-
|
|
109
|
-
|
|
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
|
-
|
|
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> <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> <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> <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
|
+
[](https://github.com/sponsors/streetsidesoftware) [](https://thanks.dev/u/gh/streetsidesoftware) [](https://opencollective.com/cspell) [](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": "
|
|
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
|
+
}
|