@mark1russell7/collections 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +78 -2
- package/build/dag/index.d.ts +144 -0
- package/build/dag/index.d.ts.map +1 -0
- package/build/dag/index.js +294 -0
- package/build/dag/index.js.map +1 -0
- package/build/graph/index.d.ts +20 -0
- package/build/graph/index.d.ts.map +1 -0
- package/build/graph/index.js +48 -0
- package/build/graph/index.js.map +1 -0
- package/build/index.d.ts +4967 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7897 -0
- package/build/index.js.map +1 -0
- package/build/testing/index.d.ts +25 -0
- package/build/testing/index.d.ts.map +1 -0
- package/build/testing/index.js +72 -0
- package/build/testing/index.js.map +1 -0
- package/package.json +77 -3
- package/src/async/async-queue.ts +481 -0
- package/src/async/channels.ts +450 -0
- package/src/async/settled.ts +41 -0
- package/src/behaviors/bounded.ts +485 -0
- package/src/behaviors/composite.ts +99 -0
- package/src/behaviors/evented.ts +464 -0
- package/src/behaviors/lru.ts +449 -0
- package/src/behaviors/readonly.ts +236 -0
- package/src/behaviors/safe.ts +358 -0
- package/src/behaviors/synchronized.ts +316 -0
- package/src/behaviors/ttl.ts +464 -0
- package/src/core/effects.ts +327 -0
- package/src/core/events.ts +363 -0
- package/src/core/middleware.ts +413 -0
- package/src/core/policies.ts +316 -0
- package/src/core/traits.ts +164 -0
- package/src/dag/builder.ts +124 -0
- package/src/dag/executor.ts +190 -0
- package/src/dag/index.ts +14 -0
- package/src/dag/traversal.ts +129 -0
- package/src/dag/types.ts +87 -0
- package/src/fx/collectors.ts +500 -0
- package/src/fx/iter.ts +536 -0
- package/src/graph/hub-order.ts +53 -0
- package/src/graph/index.ts +5 -0
- package/src/impl/array-deque.ts +463 -0
- package/src/impl/array-list.ts +490 -0
- package/src/impl/hash-map.ts +623 -0
- package/src/impl/hash-set.ts +342 -0
- package/src/impl/linked-hash-map.ts +572 -0
- package/src/impl/linked-list.ts +610 -0
- package/src/impl/priority-queue.ts +448 -0
- package/src/impl/summary-tree.ts +594 -0
- package/src/impl/tree-map.ts +913 -0
- package/src/impl/tree-set.ts +469 -0
- package/src/index.ts +237 -0
- package/src/interfaces/collection.ts +141 -0
- package/src/interfaces/list.ts +281 -0
- package/src/interfaces/map.ts +405 -0
- package/src/interfaces/queue.ts +353 -0
- package/src/interfaces/set.ts +158 -0
- package/src/order/index.ts +6 -0
- package/src/order/rank.ts +271 -0
- package/src/storage/listeners.ts +72 -0
- package/src/testing/check.ts +81 -0
- package/src/testing/index.ts +7 -0
- package/src/utils/defaults.ts +443 -0
- package/src/utils/factories.ts +357 -0
- package/src/utils/helpers.ts +248 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Go-style channels for CSP (Communicating Sequential Processes).
|
|
3
|
+
*
|
|
4
|
+
* This module gives typed, bidirectional communication channels inspired by Go.
|
|
5
|
+
* Perfect for coordinating async operations and implementing concurrent patterns.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const ch = channel<number>()
|
|
9
|
+
*
|
|
10
|
+
* // Sender
|
|
11
|
+
* await ch.send(42)
|
|
12
|
+
*
|
|
13
|
+
* // Receiver
|
|
14
|
+
* const value = await ch.receive()
|
|
15
|
+
*
|
|
16
|
+
* // Select from multiple channels
|
|
17
|
+
* const result = await select(
|
|
18
|
+
* ch1.case((v) => console.log('ch1:', v)),
|
|
19
|
+
* ch2.case((v) => console.log('ch2:', v))
|
|
20
|
+
* )
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { asyncQueue, type AsyncQueue } from "./async-queue.js";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Channel<T> - Bidirectional communication channel.
|
|
27
|
+
*
|
|
28
|
+
* The channels of Go are the model. This class gives send/receive operations
|
|
29
|
+
* that can block until the other side is ready.
|
|
30
|
+
*/
|
|
31
|
+
export class Channel<T> {
|
|
32
|
+
private queue: AsyncQueue<T>;
|
|
33
|
+
private _isClosed = false;
|
|
34
|
+
|
|
35
|
+
constructor(bufferSize: number = 0) {
|
|
36
|
+
// A buffer size of 0 is an unbuffered channel: send waits for a receiver (a rendezvous).
|
|
37
|
+
// (Before, `bufferSize || 1` gave it a buffer of 1: BUGS-2026-07 L17.)
|
|
38
|
+
this.queue = asyncQueue<T>({ capacity: bufferSize });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* This method sends a value through the channel.
|
|
43
|
+
* Blocks if channel buffer is full.
|
|
44
|
+
*
|
|
45
|
+
* @throws Error if channel is closed
|
|
46
|
+
*/
|
|
47
|
+
async send(value: T): Promise<void> {
|
|
48
|
+
if (this._isClosed) {
|
|
49
|
+
throw new Error("Cannot send on closed channel");
|
|
50
|
+
}
|
|
51
|
+
await this.queue.put(value);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* This method receives a value from the channel.
|
|
56
|
+
* Blocks if no value is available.
|
|
57
|
+
*
|
|
58
|
+
* @throws Error if channel is closed and empty
|
|
59
|
+
*/
|
|
60
|
+
async receive(): Promise<T> {
|
|
61
|
+
return await this.queue.take();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* This method waits for one value, as `receive` does, and gives it to `onValue`. When the
|
|
66
|
+
* channel is closed and empty, it calls `onClosed`. These calls are synchronous: they occur in
|
|
67
|
+
* the call that sends the value or closes the channel.
|
|
68
|
+
*
|
|
69
|
+
* The function that it gives withdraws the wait, so no later value goes to it.
|
|
70
|
+
*
|
|
71
|
+
* @returns A function that withdraws the wait. It gives true when the wait had no value yet.
|
|
72
|
+
*/
|
|
73
|
+
waitReceive(onValue: (value: T) => void, onClosed: (error: Error) => void): () => boolean {
|
|
74
|
+
return this.queue.waitTake(onValue, onClosed);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* This method tries to send without blocking.
|
|
79
|
+
* This method gives false if channel is full.
|
|
80
|
+
*/
|
|
81
|
+
trySend(value: T): boolean {
|
|
82
|
+
if (this._isClosed) return false;
|
|
83
|
+
return this.queue.tryPut(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* This method tries to receive without blocking.
|
|
88
|
+
* This method gives undefined if no value is available.
|
|
89
|
+
*/
|
|
90
|
+
tryReceive(): T | undefined {
|
|
91
|
+
return this.queue.tryTake();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* This method closes the channel. No more values can be sent.
|
|
96
|
+
* Receivers can still drain remaining values.
|
|
97
|
+
*/
|
|
98
|
+
close(): void {
|
|
99
|
+
this._isClosed = true;
|
|
100
|
+
this.queue.close();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
get isClosed(): boolean {
|
|
104
|
+
return this._isClosed;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
get size(): number {
|
|
108
|
+
return this.queue.size;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* This method makes a select case for this channel.
|
|
113
|
+
* The select() function uses this value for multiplexing.
|
|
114
|
+
*/
|
|
115
|
+
case<R>(handler: (value: T) => R): SelectCase<R> {
|
|
116
|
+
return {
|
|
117
|
+
channel: this,
|
|
118
|
+
handler,
|
|
119
|
+
tryReceive: () => this.tryReceive(),
|
|
120
|
+
receive: () => this.receive(),
|
|
121
|
+
wait: (onValue, onClosed) => this.waitReceive(onValue, onClosed),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Async iteration over channel values.
|
|
127
|
+
* Stops when channel is closed and empty.
|
|
128
|
+
*/
|
|
129
|
+
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
130
|
+
while (true) {
|
|
131
|
+
try {
|
|
132
|
+
yield await this.receive();
|
|
133
|
+
} catch (e) {
|
|
134
|
+
// Channel closed
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* SelectCase represents a case in a select statement.
|
|
143
|
+
*/
|
|
144
|
+
export interface SelectCase<R> {
|
|
145
|
+
channel: Channel<any>;
|
|
146
|
+
handler: (value: any) => R;
|
|
147
|
+
tryReceive: () => any;
|
|
148
|
+
receive: () => Promise<any>;
|
|
149
|
+
/**
|
|
150
|
+
* A wait for one value that `select` can withdraw: `Channel.waitReceive`. A case without it
|
|
151
|
+
* uses the `waitReceive` method of its channel.
|
|
152
|
+
*/
|
|
153
|
+
wait?: (onValue: (value: any) => void, onClosed: (error: Error) => void) => () => boolean;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A wait for one value that can be withdrawn, as `Channel.waitReceive` gives it. */
|
|
157
|
+
type Wait = (onValue: (value: unknown) => void, onClosed: (error: Error) => void) => () => boolean;
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* This function gives the first value of the waits, with the index of its wait. It rejects with
|
|
161
|
+
* the error of the first wait whose channel is closed and empty. It withdraws each other wait in
|
|
162
|
+
* the same call, so a later value stays in its channel. (Before, the receives of the cases that
|
|
163
|
+
* lost stayed in their channels and dropped the next value of each: audit O56.)
|
|
164
|
+
*/
|
|
165
|
+
function firstOf(waits: readonly Wait[]): Promise<{ index: number; value: unknown }> {
|
|
166
|
+
return new Promise((resolve, reject) => {
|
|
167
|
+
const withdraws: Array<() => boolean> = [];
|
|
168
|
+
let settled = false;
|
|
169
|
+
const end = (): void => {
|
|
170
|
+
settled = true;
|
|
171
|
+
for (const withdraw of withdraws) withdraw();
|
|
172
|
+
};
|
|
173
|
+
// A wait can call back at once, in its own call, when its channel has a value or is closed
|
|
174
|
+
try {
|
|
175
|
+
for (let index = 0; index < waits.length && !settled; index++) {
|
|
176
|
+
withdraws.push(
|
|
177
|
+
waits[index]!(
|
|
178
|
+
(value) => {
|
|
179
|
+
if (settled) return;
|
|
180
|
+
end();
|
|
181
|
+
resolve({ index, value });
|
|
182
|
+
},
|
|
183
|
+
(error) => {
|
|
184
|
+
if (settled) return;
|
|
185
|
+
end();
|
|
186
|
+
reject(error);
|
|
187
|
+
},
|
|
188
|
+
),
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
} catch (error) {
|
|
192
|
+
// A wait that throws: the waits before it are withdrawn
|
|
193
|
+
if (!settled) end();
|
|
194
|
+
reject(error);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Selects from multiple channels (like Go's select statement).
|
|
201
|
+
*
|
|
202
|
+
* This function waits for the first channel to have a value available,
|
|
203
|
+
* then calls its handler and gives the result.
|
|
204
|
+
*
|
|
205
|
+
* The first case with a value at once wins. The cases that lose keep no receive: a value that
|
|
206
|
+
* comes later stays in its channel for the next receiver. When the channel of a case is closed
|
|
207
|
+
* and empty, the given promise rejects.
|
|
208
|
+
*
|
|
209
|
+
* @example
|
|
210
|
+
* const result = await select(
|
|
211
|
+
* ch1.case((v) => `ch1: ${v}`),
|
|
212
|
+
* ch2.case((v) => `ch2: ${v}`),
|
|
213
|
+
* timeout(1000).case(() => 'timeout')
|
|
214
|
+
* )
|
|
215
|
+
*/
|
|
216
|
+
export async function select<R>(...cases: SelectCase<R>[]): Promise<R> {
|
|
217
|
+
const { index, value } = await firstOf(
|
|
218
|
+
cases.map((c): Wait => c.wait ?? ((onValue, onClosed) => c.channel.waitReceive(onValue, onClosed))),
|
|
219
|
+
);
|
|
220
|
+
// The handler runs after the race, not in the call of the sender
|
|
221
|
+
return cases[index]!.handler(value);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* This function makes a timeout channel that sends after the specified duration.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* const result = await select(
|
|
229
|
+
* dataChannel.case((v) => v),
|
|
230
|
+
* timeout(5000).case(() => 'timeout!')
|
|
231
|
+
* )
|
|
232
|
+
*/
|
|
233
|
+
export function timeout(ms: number): Channel<void> {
|
|
234
|
+
const ch = new Channel<void>();
|
|
235
|
+
setTimeout(() => {
|
|
236
|
+
ch.send(undefined).catch(() => {}); // Ignore if closed
|
|
237
|
+
ch.close();
|
|
238
|
+
}, ms);
|
|
239
|
+
return ch;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* This function makes a ticker channel that sends at regular intervals.
|
|
244
|
+
*
|
|
245
|
+
* @example
|
|
246
|
+
* const tick = ticker(1000) // Every second
|
|
247
|
+
* for await (const t of tick) {
|
|
248
|
+
* console.log('Tick:', t)
|
|
249
|
+
* }
|
|
250
|
+
*/
|
|
251
|
+
export function ticker(ms: number): Channel<number> & { stop: () => void } {
|
|
252
|
+
const ch = new Channel<number>(1);
|
|
253
|
+
let count = 0;
|
|
254
|
+
|
|
255
|
+
const intervalId = setInterval(() => {
|
|
256
|
+
ch.trySend(count++);
|
|
257
|
+
}, ms);
|
|
258
|
+
|
|
259
|
+
return Object.assign(ch, {
|
|
260
|
+
stop: () => {
|
|
261
|
+
clearInterval(intervalId);
|
|
262
|
+
ch.close();
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Pipeline: pipes values from input channel through transform to output channel.
|
|
269
|
+
*
|
|
270
|
+
* @example
|
|
271
|
+
* const input = channel<number>()
|
|
272
|
+
* const output = pipeline(input, (x) => x * 2)
|
|
273
|
+
*
|
|
274
|
+
* await input.send(5)
|
|
275
|
+
* const result = await output.receive() // 10
|
|
276
|
+
*/
|
|
277
|
+
export function pipeline<T, U>(
|
|
278
|
+
input: Channel<T>,
|
|
279
|
+
transform: (value: T) => U | Promise<U>,
|
|
280
|
+
bufferSize: number = 0
|
|
281
|
+
): Channel<U> {
|
|
282
|
+
const output = new Channel<U>(bufferSize);
|
|
283
|
+
|
|
284
|
+
// The output closes also when the transform fails, so its reader does not wait forever. The
|
|
285
|
+
// error goes to the console, as in workerPool. (Before, it was an unhandled rejection: audit pass 2.)
|
|
286
|
+
(async () => {
|
|
287
|
+
try {
|
|
288
|
+
for await (const value of input) {
|
|
289
|
+
const transformed = await transform(value);
|
|
290
|
+
await output.send(transformed);
|
|
291
|
+
}
|
|
292
|
+
} finally {
|
|
293
|
+
output.close();
|
|
294
|
+
}
|
|
295
|
+
})().catch((error: unknown) => console.error("pipeline error:", error));
|
|
296
|
+
|
|
297
|
+
return output;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Fan-out: distributes values from one input channel to multiple output channels.
|
|
302
|
+
*
|
|
303
|
+
* @example
|
|
304
|
+
* const input = channel<number>()
|
|
305
|
+
* const [out1, out2, out3] = fanOut(input, 3)
|
|
306
|
+
*
|
|
307
|
+
* // Each output gets a copy of every input value
|
|
308
|
+
*/
|
|
309
|
+
export function fanOut<T>(input: Channel<T>, count: number, bufferSize: number = 0): Channel<T>[] {
|
|
310
|
+
const outputs = Array.from({ length: count }, () => new Channel<T>(bufferSize));
|
|
311
|
+
|
|
312
|
+
(async () => {
|
|
313
|
+
try {
|
|
314
|
+
for await (const value of input) {
|
|
315
|
+
await Promise.all(outputs.map((ch) => ch.send(value)));
|
|
316
|
+
}
|
|
317
|
+
} finally {
|
|
318
|
+
outputs.forEach((ch) => ch.close());
|
|
319
|
+
}
|
|
320
|
+
})().catch((error: unknown) => console.error("fanOut error:", error));
|
|
321
|
+
|
|
322
|
+
return outputs;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Fan-in: merges multiple input channels into one output channel.
|
|
327
|
+
*
|
|
328
|
+
* @example
|
|
329
|
+
* const ch1 = channel<number>()
|
|
330
|
+
* const ch2 = channel<number>()
|
|
331
|
+
* const merged = fanIn(ch1, ch2)
|
|
332
|
+
*
|
|
333
|
+
* // merged receives values from both ch1 and ch2
|
|
334
|
+
*/
|
|
335
|
+
export function fanIn<T>(...inputs: Channel<T>[]): Channel<T> {
|
|
336
|
+
const output = new Channel<T>();
|
|
337
|
+
|
|
338
|
+
const workers = inputs.map(async (input) => {
|
|
339
|
+
for await (const value of input) {
|
|
340
|
+
await output.send(value);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// All the workers settle, then the output closes, also after a failed send
|
|
345
|
+
Promise.allSettled(workers).then((results) => {
|
|
346
|
+
output.close();
|
|
347
|
+
for (const result of results) if (result.status === "rejected") console.error("fanIn error:", result.reason);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
return output;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Merge: like fanIn but closes output when first input closes.
|
|
355
|
+
*
|
|
356
|
+
* It takes one value at a time, from the inputs in turn. It keeps no receive on an input while
|
|
357
|
+
* it waits for the reader of the output. Thus each value of each input reaches the output one
|
|
358
|
+
* time, in the order of its input, or stays in its input.
|
|
359
|
+
*/
|
|
360
|
+
export function merge<T>(...inputs: Channel<T>[]): Channel<T> {
|
|
361
|
+
const output = new Channel<T>();
|
|
362
|
+
|
|
363
|
+
(async () => {
|
|
364
|
+
// The input after the input of the last value comes first, so a busy input starves no other
|
|
365
|
+
let start = 0;
|
|
366
|
+
while (true) {
|
|
367
|
+
const order = inputs.map((_, offset) => (start + offset) % inputs.length);
|
|
368
|
+
let next: { index: number; value: unknown };
|
|
369
|
+
try {
|
|
370
|
+
next = await firstOf(order.map((index): Wait => (onValue, onClosed) => inputs[index]!.waitReceive(onValue, onClosed)));
|
|
371
|
+
} catch {
|
|
372
|
+
// An input is closed and empty
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
const index = order[next.index]!;
|
|
376
|
+
start = (index + 1) % inputs.length;
|
|
377
|
+
try {
|
|
378
|
+
await output.send(next.value as T);
|
|
379
|
+
} catch {
|
|
380
|
+
// The reader closed the output
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
output.close();
|
|
385
|
+
})();
|
|
386
|
+
|
|
387
|
+
return output;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Buffered channel with specified capacity.
|
|
392
|
+
*/
|
|
393
|
+
export function buffered<T>(capacity: number): Channel<T> {
|
|
394
|
+
return new Channel<T>(capacity);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Unbuffered channel (rendezvous point).
|
|
399
|
+
* Sends block until receiver is ready.
|
|
400
|
+
*/
|
|
401
|
+
export function unbuffered<T>(): Channel<T> {
|
|
402
|
+
return new Channel<T>(0);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Factory function to make a channel.
|
|
407
|
+
*
|
|
408
|
+
* @example
|
|
409
|
+
* const ch = channel<number>()
|
|
410
|
+
* const bufferedCh = channel<string>(10)
|
|
411
|
+
*/
|
|
412
|
+
export function channel<T>(bufferSize: number = 0): Channel<T> {
|
|
413
|
+
return new Channel<T>(bufferSize);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* WorkerPool: distributes work across multiple workers.
|
|
418
|
+
*
|
|
419
|
+
* @example
|
|
420
|
+
* const pool = workerPool(
|
|
421
|
+
* jobChannel,
|
|
422
|
+
* async (job) => await processJob(job),
|
|
423
|
+
* { workers: 4 }
|
|
424
|
+
* )
|
|
425
|
+
*
|
|
426
|
+
* // 4 workers concurrently process jobs from jobChannel
|
|
427
|
+
*/
|
|
428
|
+
export function workerPool<T, R>(
|
|
429
|
+
jobs: Channel<T>,
|
|
430
|
+
worker: (job: T) => Promise<R>,
|
|
431
|
+
options: { workers: number; bufferSize?: number } = { workers: 1 }
|
|
432
|
+
): Channel<R> {
|
|
433
|
+
const results = new Channel<R>(options.bufferSize || 0);
|
|
434
|
+
const { workers: workerCount } = options;
|
|
435
|
+
|
|
436
|
+
const workers = Array.from({ length: workerCount }, async () => {
|
|
437
|
+
for await (const job of jobs) {
|
|
438
|
+
try {
|
|
439
|
+
const result = await worker(job);
|
|
440
|
+
await results.send(result);
|
|
441
|
+
} catch (error) {
|
|
442
|
+
console.error("Worker error:", error);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
Promise.all(workers).then(() => results.close());
|
|
448
|
+
|
|
449
|
+
return results;
|
|
450
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* asSettled - The results of running promises, in the order that they settle.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* const pages = urls.map((url) => fetch(url));
|
|
6
|
+
* for await (const result of asSettled(pages)) {
|
|
7
|
+
* if (result.status === "fulfilled") show(result.index, result.value);
|
|
8
|
+
* else report(result.index, result.reason);
|
|
9
|
+
* }
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** One result of `asSettled`: the index of its promise in the input, and how the promise settled. */
|
|
13
|
+
export type Settled<T> = { readonly index: number } & PromiseSettledResult<T>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* This function gives the result of each promise when it settles, in settle order, not in input
|
|
17
|
+
* order. The promises run already: this function starts nothing. Each result has the index of its
|
|
18
|
+
* promise in the input. A rejected promise gives `status: "rejected"` and its reason: the
|
|
19
|
+
* generator does not throw it. When the consumer stops early, the other promises continue, and
|
|
20
|
+
* their rejections are not reported as unhandled.
|
|
21
|
+
*/
|
|
22
|
+
export async function* asSettled<T>(promises: Iterable<Promise<T>>): AsyncGenerator<Settled<T>, void, undefined> {
|
|
23
|
+
const pending = new Map<number, Promise<Settled<T>>>();
|
|
24
|
+
let next = 0;
|
|
25
|
+
for (const promise of promises) {
|
|
26
|
+
const index = next;
|
|
27
|
+
next += 1;
|
|
28
|
+
pending.set(
|
|
29
|
+
index,
|
|
30
|
+
Promise.resolve(promise).then(
|
|
31
|
+
(value): Settled<T> => ({ index, status: "fulfilled", value }),
|
|
32
|
+
(reason: unknown): Settled<T> => ({ index, status: "rejected", reason })
|
|
33
|
+
)
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
while (pending.size > 0) {
|
|
37
|
+
const settled = await Promise.race(pending.values());
|
|
38
|
+
pending.delete(settled.index);
|
|
39
|
+
yield settled;
|
|
40
|
+
}
|
|
41
|
+
}
|