@procedures/collections 0.47.1 → 0.48.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 (238) hide show
  1. package/CHANGELOG.md +32 -8
  2. package/README.md +3 -1
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/index.d.ts +1 -59
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +3 -95
  7. package/dist/index.js.map +1 -1
  8. package/dist/storage/index.d.ts +2 -2
  9. package/dist/storage/index.d.ts.map +1 -1
  10. package/dist/storage/index.js +1 -1
  11. package/dist/storage/index.js.map +1 -1
  12. package/dist/storage/memory.d.ts +1 -1
  13. package/dist/storage/memory.d.ts.map +1 -1
  14. package/dist/storage/memory.js +1 -1
  15. package/dist/storage/memory.js.map +1 -1
  16. package/dist/testing/index.d.ts +1 -1
  17. package/dist/testing/index.d.ts.map +1 -1
  18. package/dist/testing/index.js +1 -1
  19. package/dist/testing/index.js.map +1 -1
  20. package/dist/testing/storage-contract.js +1 -1
  21. package/dist/testing/storage-contract.js.map +1 -1
  22. package/dist/undo/index.d.ts +1 -1
  23. package/dist/undo/index.js +1 -1
  24. package/dist/undo/undo-log.d.ts +1 -1
  25. package/dist/undo/undo-log.js +1 -1
  26. package/package.json +5 -5
  27. package/src/index.ts +338 -214
  28. package/src/storage/index.ts +2 -2
  29. package/src/storage/memory.ts +1 -1
  30. package/src/testing/index.ts +1 -1
  31. package/src/testing/storage-contract.ts +1 -1
  32. package/src/undo/index.ts +1 -1
  33. package/src/undo/undo-log.ts +1 -1
  34. package/dist/async/async-queue.d.ts +0 -170
  35. package/dist/async/async-queue.d.ts.map +0 -1
  36. package/dist/async/async-queue.js +0 -404
  37. package/dist/async/async-queue.js.map +0 -1
  38. package/dist/async/channels.d.ts +0 -211
  39. package/dist/async/channels.d.ts.map +0 -1
  40. package/dist/async/channels.js +0 -393
  41. package/dist/async/channels.js.map +0 -1
  42. package/dist/async/settled.d.ts +0 -23
  43. package/dist/async/settled.d.ts.map +0 -1
  44. package/dist/async/settled.js +0 -32
  45. package/dist/async/settled.js.map +0 -1
  46. package/dist/behaviors/bounded.d.ts +0 -79
  47. package/dist/behaviors/bounded.d.ts.map +0 -1
  48. package/dist/behaviors/bounded.js +0 -393
  49. package/dist/behaviors/bounded.js.map +0 -1
  50. package/dist/behaviors/composite.d.ts +0 -17
  51. package/dist/behaviors/composite.d.ts.map +0 -1
  52. package/dist/behaviors/composite.js +0 -93
  53. package/dist/behaviors/composite.js.map +0 -1
  54. package/dist/behaviors/evented.d.ts +0 -154
  55. package/dist/behaviors/evented.d.ts.map +0 -1
  56. package/dist/behaviors/evented.js +0 -299
  57. package/dist/behaviors/evented.js.map +0 -1
  58. package/dist/behaviors/lru.d.ts +0 -84
  59. package/dist/behaviors/lru.d.ts.map +0 -1
  60. package/dist/behaviors/lru.js +0 -376
  61. package/dist/behaviors/lru.js.map +0 -1
  62. package/dist/behaviors/readonly.d.ts +0 -73
  63. package/dist/behaviors/readonly.d.ts.map +0 -1
  64. package/dist/behaviors/readonly.js +0 -189
  65. package/dist/behaviors/readonly.js.map +0 -1
  66. package/dist/behaviors/safe.d.ts +0 -163
  67. package/dist/behaviors/safe.d.ts.map +0 -1
  68. package/dist/behaviors/safe.js +0 -176
  69. package/dist/behaviors/safe.js.map +0 -1
  70. package/dist/behaviors/synchronized.d.ts +0 -88
  71. package/dist/behaviors/synchronized.d.ts.map +0 -1
  72. package/dist/behaviors/synchronized.js +0 -285
  73. package/dist/behaviors/synchronized.js.map +0 -1
  74. package/dist/behaviors/ttl.d.ts +0 -118
  75. package/dist/behaviors/ttl.d.ts.map +0 -1
  76. package/dist/behaviors/ttl.js +0 -354
  77. package/dist/behaviors/ttl.js.map +0 -1
  78. package/dist/contracts/model.d.ts +0 -29
  79. package/dist/contracts/model.d.ts.map +0 -1
  80. package/dist/contracts/model.js +0 -26
  81. package/dist/contracts/model.js.map +0 -1
  82. package/dist/core/effects.d.ts +0 -176
  83. package/dist/core/effects.d.ts.map +0 -1
  84. package/dist/core/effects.js +0 -180
  85. package/dist/core/effects.js.map +0 -1
  86. package/dist/core/events.d.ts +0 -192
  87. package/dist/core/events.d.ts.map +0 -1
  88. package/dist/core/events.js +0 -291
  89. package/dist/core/events.js.map +0 -1
  90. package/dist/core/middleware.d.ts +0 -231
  91. package/dist/core/middleware.d.ts.map +0 -1
  92. package/dist/core/middleware.js +0 -161
  93. package/dist/core/middleware.js.map +0 -1
  94. package/dist/core/policies.d.ts +0 -220
  95. package/dist/core/policies.d.ts.map +0 -1
  96. package/dist/core/policies.js +0 -48
  97. package/dist/core/policies.js.map +0 -1
  98. package/dist/core/traits.d.ts +0 -142
  99. package/dist/core/traits.d.ts.map +0 -1
  100. package/dist/core/traits.js +0 -8
  101. package/dist/core/traits.js.map +0 -1
  102. package/dist/fx/collectors.d.ts +0 -193
  103. package/dist/fx/collectors.d.ts.map +0 -1
  104. package/dist/fx/collectors.js +0 -375
  105. package/dist/fx/collectors.js.map +0 -1
  106. package/dist/fx/iter.d.ts +0 -166
  107. package/dist/fx/iter.d.ts.map +0 -1
  108. package/dist/fx/iter.js +0 -421
  109. package/dist/fx/iter.js.map +0 -1
  110. package/dist/impl/array-deque.d.ts +0 -112
  111. package/dist/impl/array-deque.d.ts.map +0 -1
  112. package/dist/impl/array-deque.js +0 -380
  113. package/dist/impl/array-deque.js.map +0 -1
  114. package/dist/impl/array-list.d.ts +0 -101
  115. package/dist/impl/array-list.d.ts.map +0 -1
  116. package/dist/impl/array-list.js +0 -387
  117. package/dist/impl/array-list.js.map +0 -1
  118. package/dist/impl/hash-map.d.ts +0 -149
  119. package/dist/impl/hash-map.d.ts.map +0 -1
  120. package/dist/impl/hash-map.js +0 -473
  121. package/dist/impl/hash-map.js.map +0 -1
  122. package/dist/impl/hash-set.d.ts +0 -125
  123. package/dist/impl/hash-set.d.ts.map +0 -1
  124. package/dist/impl/hash-set.js +0 -264
  125. package/dist/impl/hash-set.js.map +0 -1
  126. package/dist/impl/linked-hash-map.d.ts +0 -141
  127. package/dist/impl/linked-hash-map.d.ts.map +0 -1
  128. package/dist/impl/linked-hash-map.js +0 -442
  129. package/dist/impl/linked-hash-map.js.map +0 -1
  130. package/dist/impl/linked-list.d.ts +0 -109
  131. package/dist/impl/linked-list.d.ts.map +0 -1
  132. package/dist/impl/linked-list.js +0 -494
  133. package/dist/impl/linked-list.js.map +0 -1
  134. package/dist/impl/priority-queue.d.ts +0 -139
  135. package/dist/impl/priority-queue.d.ts.map +0 -1
  136. package/dist/impl/priority-queue.js +0 -343
  137. package/dist/impl/priority-queue.js.map +0 -1
  138. package/dist/impl/summary-tree.d.ts +0 -146
  139. package/dist/impl/summary-tree.d.ts.map +0 -1
  140. package/dist/impl/summary-tree.js +0 -524
  141. package/dist/impl/summary-tree.js.map +0 -1
  142. package/dist/impl/tree-map.d.ts +0 -153
  143. package/dist/impl/tree-map.d.ts.map +0 -1
  144. package/dist/impl/tree-map.js +0 -788
  145. package/dist/impl/tree-map.js.map +0 -1
  146. package/dist/impl/tree-set.d.ts +0 -112
  147. package/dist/impl/tree-set.d.ts.map +0 -1
  148. package/dist/impl/tree-set.js +0 -374
  149. package/dist/impl/tree-set.js.map +0 -1
  150. package/dist/interfaces/collection.d.ts +0 -119
  151. package/dist/interfaces/collection.d.ts.map +0 -1
  152. package/dist/interfaces/collection.js +0 -8
  153. package/dist/interfaces/collection.js.map +0 -1
  154. package/dist/interfaces/list.d.ts +0 -247
  155. package/dist/interfaces/list.d.ts.map +0 -1
  156. package/dist/interfaces/list.js +0 -8
  157. package/dist/interfaces/list.js.map +0 -1
  158. package/dist/interfaces/map.d.ts +0 -344
  159. package/dist/interfaces/map.d.ts.map +0 -1
  160. package/dist/interfaces/map.js +0 -8
  161. package/dist/interfaces/map.js.map +0 -1
  162. package/dist/interfaces/queue.d.ts +0 -304
  163. package/dist/interfaces/queue.d.ts.map +0 -1
  164. package/dist/interfaces/queue.js +0 -8
  165. package/dist/interfaces/queue.js.map +0 -1
  166. package/dist/interfaces/set.d.ts +0 -137
  167. package/dist/interfaces/set.d.ts.map +0 -1
  168. package/dist/interfaces/set.js +0 -8
  169. package/dist/interfaces/set.js.map +0 -1
  170. package/dist/order/index.d.ts +0 -7
  171. package/dist/order/index.d.ts.map +0 -1
  172. package/dist/order/index.js +0 -7
  173. package/dist/order/index.js.map +0 -1
  174. package/dist/order/rank.d.ts +0 -100
  175. package/dist/order/rank.d.ts.map +0 -1
  176. package/dist/order/rank.js +0 -286
  177. package/dist/order/rank.js.map +0 -1
  178. package/dist/storage/listeners.d.ts +0 -39
  179. package/dist/storage/listeners.d.ts.map +0 -1
  180. package/dist/storage/listeners.js +0 -65
  181. package/dist/storage/listeners.js.map +0 -1
  182. package/dist/testing/check.d.ts +0 -25
  183. package/dist/testing/check.d.ts.map +0 -1
  184. package/dist/testing/check.js +0 -85
  185. package/dist/testing/check.js.map +0 -1
  186. package/dist/utils/defaults.d.ts +0 -135
  187. package/dist/utils/defaults.d.ts.map +0 -1
  188. package/dist/utils/defaults.js +0 -322
  189. package/dist/utils/defaults.js.map +0 -1
  190. package/dist/utils/factories.d.ts +0 -144
  191. package/dist/utils/factories.d.ts.map +0 -1
  192. package/dist/utils/factories.js +0 -293
  193. package/dist/utils/factories.js.map +0 -1
  194. package/dist/utils/helpers.d.ts +0 -137
  195. package/dist/utils/helpers.d.ts.map +0 -1
  196. package/dist/utils/helpers.js +0 -221
  197. package/dist/utils/helpers.js.map +0 -1
  198. package/src/async/async-queue.ts +0 -481
  199. package/src/async/channels.ts +0 -450
  200. package/src/async/settled.ts +0 -41
  201. package/src/behaviors/bounded.ts +0 -485
  202. package/src/behaviors/composite.ts +0 -99
  203. package/src/behaviors/evented.ts +0 -464
  204. package/src/behaviors/lru.ts +0 -447
  205. package/src/behaviors/readonly.ts +0 -236
  206. package/src/behaviors/safe.ts +0 -372
  207. package/src/behaviors/synchronized.ts +0 -316
  208. package/src/behaviors/ttl.ts +0 -462
  209. package/src/contracts/model.ts +0 -44
  210. package/src/core/effects.ts +0 -323
  211. package/src/core/events.ts +0 -356
  212. package/src/core/middleware.ts +0 -415
  213. package/src/core/policies.ts +0 -316
  214. package/src/core/traits.ts +0 -164
  215. package/src/fx/collectors.ts +0 -500
  216. package/src/fx/iter.ts +0 -536
  217. package/src/impl/array-deque.ts +0 -463
  218. package/src/impl/array-list.ts +0 -490
  219. package/src/impl/hash-map.ts +0 -623
  220. package/src/impl/hash-set.ts +0 -342
  221. package/src/impl/linked-hash-map.ts +0 -572
  222. package/src/impl/linked-list.ts +0 -606
  223. package/src/impl/priority-queue.ts +0 -448
  224. package/src/impl/summary-tree.ts +0 -586
  225. package/src/impl/tree-map.ts +0 -912
  226. package/src/impl/tree-set.ts +0 -469
  227. package/src/interfaces/collection.ts +0 -141
  228. package/src/interfaces/list.ts +0 -281
  229. package/src/interfaces/map.ts +0 -405
  230. package/src/interfaces/queue.ts +0 -353
  231. package/src/interfaces/set.ts +0 -158
  232. package/src/order/index.ts +0 -6
  233. package/src/order/rank.ts +0 -271
  234. package/src/storage/listeners.ts +0 -72
  235. package/src/testing/check.ts +0 -81
  236. package/src/utils/defaults.ts +0 -345
  237. package/src/utils/factories.ts +0 -357
  238. package/src/utils/helpers.ts +0 -248
@@ -1,481 +0,0 @@
1
- /**
2
- * AsyncQueue - An async iterable queue with backpressure support.
3
- *
4
- * Designed for producer-consumer patterns where producers can wait when
5
- * the queue is full and consumers can wait when the queue is empty.
6
- * Implements AsyncIterable for use with for-await-of loops.
7
- *
8
- * @example
9
- * const queue = asyncQueue<number>({ capacity: 10 })
10
- *
11
- * // Producer
12
- * await queue.put(42) // Waits if queue is full
13
- *
14
- * // Consumer
15
- * const value = await queue.take() // Waits if queue is empty
16
- *
17
- * // Async iteration
18
- * for await (const value of queue) {
19
- * console.log(value)
20
- * }
21
- */
22
-
23
- import type { AsyncQueue as IAsyncQueue } from "../interfaces/queue.js";
24
-
25
- /**
26
- * Options for creating an AsyncQueue.
27
- */
28
- export interface AsyncQueueOptions {
29
- /**
30
- * Maximum capacity. Infinity for unbounded queue.
31
- * @default Infinity
32
- */
33
- capacity?: number;
34
-
35
- /**
36
- * Timeout for put/take operations in milliseconds.
37
- * @default undefined (no timeout)
38
- */
39
- timeout?: number;
40
- }
41
-
42
- /**
43
- * Resolver for waiting operations.
44
- */
45
- interface Resolver<T> {
46
- resolve: (value: T) => void;
47
- reject: (reason: any) => void;
48
- timeoutId?: ReturnType<typeof setTimeout>;
49
- }
50
-
51
- /** A waiting put: it keeps its element until the queue takes it. */
52
- interface Putter<T> extends Resolver<void> {
53
- element: T;
54
- }
55
-
56
- /**
57
- * AsyncQueue<T> - Thread-safe async queue with backpressure.
58
- *
59
- * Features:
60
- * - Blocking put() when full (backpressure)
61
- * - Blocking take() when empty
62
- * - AsyncIterable support
63
- * - Graceful closing
64
- * - Timeouts
65
- *
66
- * Perfect for:
67
- * - Producer-consumer patterns
68
- * - Rate limiting
69
- * - Task queues
70
- * - Stream processing
71
- */
72
- export class AsyncQueue<T> implements IAsyncQueue<T> {
73
- private buffer: T[] = [];
74
- private putters: Putter<T>[] = [];
75
- private takers: Resolver<T>[] = [];
76
- /** The calls of `peek` that wait: they see the next element, but they do not take it. */
77
- private peekers: Resolver<T>[] = [];
78
- private _isClosed = false;
79
- private readonly capacity: number;
80
- private readonly defaultTimeout?: number;
81
-
82
- constructor(options: AsyncQueueOptions = {}) {
83
- this.capacity = options.capacity ?? Infinity;
84
- if (options.timeout !== undefined) {
85
- this.defaultTimeout = options.timeout;
86
- }
87
- }
88
-
89
- // ========================================================================
90
- // Size and state
91
- // ========================================================================
92
-
93
- get size(): number {
94
- return this.buffer.length;
95
- }
96
-
97
- get isEmpty(): boolean {
98
- return this.buffer.length === 0;
99
- }
100
-
101
- get isFull(): boolean {
102
- return this.buffer.length >= this.capacity;
103
- }
104
-
105
- get isClosed(): boolean {
106
- return this._isClosed;
107
- }
108
-
109
- get remainingCapacity(): number {
110
- return this.capacity === Infinity ? Infinity : this.capacity - this.buffer.length;
111
- }
112
-
113
- // ========================================================================
114
- // Blocking operations
115
- // ========================================================================
116
-
117
- /**
118
- * Adds an element to the queue.
119
- * If the queue is full, waits until space is available. With a capacity of 0, it waits until
120
- * a taker takes the element (a rendezvous).
121
- *
122
- * @throws Error if queue is closed
123
- * @throws Error if timeout expires
124
- */
125
- async put(element: T, timeout?: number): Promise<void> {
126
- if (this._isClosed) {
127
- throw new Error("Queue is closed");
128
- }
129
- if (this.tryPutNow(element)) {
130
- return;
131
- }
132
-
133
- // A waiting peek sees the element of a waiting put (a capacity of 0)
134
- this.wakePeekers(element);
135
-
136
- // Queue is full: wait with the element. (Before, a waiting putter kept only its resolve
137
- // function, so its element was dropped when space came: BUGS-2026-07 C11.)
138
- return new Promise<void>((resolve, reject) => {
139
- const putter: Putter<T> = { element, resolve, reject };
140
- const timeoutMs = timeout ?? this.defaultTimeout;
141
- if (timeoutMs !== undefined) {
142
- putter.timeoutId = setTimeout(() => {
143
- const index = this.putters.indexOf(putter);
144
- if (index !== -1) {
145
- this.putters.splice(index, 1);
146
- }
147
- reject(new Error(`Put timeout after ${timeoutMs}ms`));
148
- }, timeoutMs);
149
- }
150
- this.putters.push(putter);
151
- });
152
- }
153
-
154
- /**
155
- * Removes and returns an element from the queue.
156
- * If the queue is empty, waits until an element is available.
157
- *
158
- * @throws Error if queue is closed and empty
159
- * @throws Error if timeout expires
160
- */
161
- async take(timeout?: number): Promise<T> {
162
- const next = this.takeNow();
163
- if (next.found) {
164
- return next.element;
165
- }
166
-
167
- // If closed and empty, throw
168
- if (this._isClosed) {
169
- throw new Error("Queue is closed and empty");
170
- }
171
-
172
- // Wait for an element
173
- return new Promise<T>((resolve, reject) => {
174
- const taker: Resolver<T> = { resolve, reject };
175
- const timeoutMs = timeout ?? this.defaultTimeout;
176
- if (timeoutMs !== undefined) {
177
- taker.timeoutId = setTimeout(() => {
178
- const index = this.takers.indexOf(taker);
179
- if (index !== -1) {
180
- this.takers.splice(index, 1);
181
- }
182
- reject(new Error(`Take timeout after ${timeoutMs}ms`));
183
- }, timeoutMs);
184
- }
185
- this.takers.push(taker);
186
- });
187
- }
188
-
189
- /**
190
- * This method waits for the next element, as `take` does, but it gives the element to
191
- * `onElement` and the closure of the queue to `onClosed`. These calls are synchronous: they
192
- * occur in the call that adds the element or closes the queue. The method has no timeout.
193
- *
194
- * The function that it returns withdraws the wait. A withdrawn wait gets no element, so no
195
- * element goes to a taker that left. `select` races its cases with this method.
196
- *
197
- * @returns A function that withdraws the wait. It returns true when the wait had no element yet.
198
- */
199
- waitTake(onElement: (element: T) => void, onClosed: (error: Error) => void): () => boolean {
200
- const next = this.takeNow();
201
- if (next.found) {
202
- onElement(next.element);
203
- return () => false;
204
- }
205
- if (this._isClosed) {
206
- onClosed(new Error("Queue is closed and empty"));
207
- return () => false;
208
- }
209
- const taker: Resolver<T> = { resolve: onElement, reject: onClosed };
210
- this.takers.push(taker);
211
- return () => {
212
- const index = this.takers.indexOf(taker);
213
- if (index === -1) return false;
214
- this.takers.splice(index, 1);
215
- return true;
216
- };
217
- }
218
-
219
- // ========================================================================
220
- // Non-blocking operations
221
- // ========================================================================
222
-
223
- /**
224
- * Attempts to add an element without waiting.
225
- * Returns false if queue is full (with a capacity of 0: if no taker waits).
226
- */
227
- tryPut(element: T): boolean {
228
- if (this._isClosed) {
229
- return false;
230
- }
231
- return this.tryPutNow(element);
232
- }
233
-
234
- /**
235
- * Attempts to remove an element without waiting.
236
- * Returns undefined if queue is empty.
237
- */
238
- tryTake(): T | undefined {
239
- const next = this.takeNow();
240
- return next.found ? next.element : undefined;
241
- }
242
-
243
- /** Gives the element to a waiting taker, or puts it in the buffer when there is space. */
244
- private tryPutNow(element: T): boolean {
245
- // A waiting taker gets the element directly (the buffer is empty when a taker waits)
246
- const taker = this.takers.shift();
247
- if (taker) {
248
- this.wakePeekers(element);
249
- this.clearTimeout(taker);
250
- taker.resolve(element);
251
- return true;
252
- }
253
- if (this.buffer.length < this.capacity) {
254
- this.buffer.push(element);
255
- this.wakePeekers(element);
256
- return true;
257
- }
258
- return false;
259
- }
260
-
261
- /** Each waiting peek gets the element, which stays where it is. */
262
- private wakePeekers(element: T): void {
263
- const peekers = this.peekers;
264
- this.peekers = [];
265
- for (const peeker of peekers) {
266
- this.clearTimeout(peeker);
267
- peeker.resolve(element);
268
- }
269
- }
270
-
271
- /**
272
- * Takes the next element: from the buffer (then a waiting putter moves its element into the
273
- * buffer), or directly from a waiting putter (a capacity of 0). (Before, the direct path
274
- * released the putter but never gave its element to the taker, so the taker waited forever:
275
- * BUGS-2026-07 C11.)
276
- */
277
- private takeNow(): { found: true; element: T } | { found: false } {
278
- if (this.buffer.length > 0) {
279
- const element = this.buffer.shift()!;
280
- this.admitPutter();
281
- return { found: true, element };
282
- }
283
- const putter = this.putters.shift();
284
- if (putter) {
285
- this.clearTimeout(putter);
286
- putter.resolve();
287
- return { found: true, element: putter.element };
288
- }
289
- return { found: false };
290
- }
291
-
292
- // ========================================================================
293
- // Peeking
294
- // ========================================================================
295
-
296
- /**
297
- * Returns the next element without removing it.
298
- * Waits if queue is empty.
299
- */
300
- async peek(): Promise<T> {
301
- if (this.buffer.length > 0) {
302
- return this.buffer[0]!;
303
- }
304
- if (this.putters.length > 0) {
305
- return this.putters[0]!.element;
306
- }
307
-
308
- if (this._isClosed) {
309
- throw new Error("Queue is closed and empty");
310
- }
311
-
312
- // Wait for the next element without a take. (Before, peek took the element and put it back
313
- // at the front: a take that waited after it kept waiting, and the order changed: audit pass 2.)
314
- return new Promise<T>((resolve, reject) => {
315
- const peeker: Resolver<T> = { resolve, reject };
316
- const timeoutMs = this.defaultTimeout;
317
- if (timeoutMs !== undefined) {
318
- peeker.timeoutId = setTimeout(() => {
319
- const index = this.peekers.indexOf(peeker);
320
- if (index !== -1) {
321
- this.peekers.splice(index, 1);
322
- }
323
- reject(new Error(`Peek timeout after ${timeoutMs}ms`));
324
- }, timeoutMs);
325
- }
326
- this.peekers.push(peeker);
327
- });
328
- }
329
-
330
- /**
331
- * Returns the next element without waiting.
332
- * Returns undefined if queue is empty.
333
- */
334
- tryPeek(): T | undefined {
335
- return this.buffer.length > 0 ? this.buffer[0] : this.putters[0]?.element;
336
- }
337
-
338
- // ========================================================================
339
- // Closing and draining
340
- // ========================================================================
341
-
342
- /**
343
- * Closes the queue. No more elements can be added.
344
- * Existing elements can still be consumed.
345
- */
346
- close(): void {
347
- this._isClosed = true;
348
-
349
- // Reject all waiting putters
350
- for (const putter of this.putters) {
351
- this.clearTimeout(putter);
352
- putter.reject(new Error("Queue closed"));
353
- }
354
- this.putters = [];
355
-
356
- // Wake up takers if queue is empty
357
- if (this.buffer.length === 0) {
358
- for (const taker of this.takers) {
359
- this.clearTimeout(taker);
360
- taker.reject(new Error("Queue closed and empty"));
361
- }
362
- this.takers = [];
363
- for (const peeker of this.peekers) {
364
- this.clearTimeout(peeker);
365
- peeker.reject(new Error("Queue closed and empty"));
366
- }
367
- this.peekers = [];
368
- }
369
- }
370
-
371
- /**
372
- * Drains all elements into an array.
373
- * Returns immediately with current elements.
374
- */
375
- drain(): T[] {
376
- // The buffer, then the elements of the waiting putters, in order. (Before, the waiting
377
- // putters were released but their elements were dropped.)
378
- const elements = this.buffer.slice();
379
- this.buffer = [];
380
- for (const putter of this.putters.splice(0)) {
381
- this.clearTimeout(putter);
382
- putter.resolve();
383
- elements.push(putter.element);
384
- }
385
- return elements;
386
- }
387
-
388
- // ========================================================================
389
- // Async iteration
390
- // ========================================================================
391
-
392
- /**
393
- * Async iterator that yields elements as they become available.
394
- * Stops when queue is closed and empty.
395
- */
396
- async *[Symbol.asyncIterator](): AsyncIterator<T> {
397
- while (true) {
398
- const next = this.takeNow();
399
- if (next.found) {
400
- yield next.element;
401
- } else if (this._isClosed) {
402
- break;
403
- } else {
404
- let element: T;
405
- try {
406
- element = await this.take();
407
- } catch (error) {
408
- // The queue was closed while the iterator waited
409
- if (this._isClosed) break;
410
- throw error;
411
- }
412
- yield element;
413
- }
414
- }
415
- }
416
-
417
- // ========================================================================
418
- // Private helpers
419
- // ========================================================================
420
-
421
- /** When the buffer has space, the first waiting putter moves its element into it. */
422
- private admitPutter(): void {
423
- if (this.putters.length > 0 && this.buffer.length < this.capacity) {
424
- const putter = this.putters.shift()!;
425
- this.clearTimeout(putter);
426
- this.buffer.push(putter.element);
427
- putter.resolve();
428
- }
429
- }
430
-
431
- private clearTimeout(resolver: Resolver<any>): void {
432
- if (resolver.timeoutId) {
433
- clearTimeout(resolver.timeoutId);
434
- }
435
- }
436
-
437
- // ========================================================================
438
- // Utility methods
439
- // ========================================================================
440
-
441
- /**
442
- * Returns statistics about the queue.
443
- */
444
- getStats() : {
445
- size: number;
446
- capacity: number;
447
- isEmpty: boolean;
448
- isFull: boolean;
449
- isClosed: boolean;
450
- waitingPutters: number;
451
- waitingTakers: number;
452
- remainingCapacity: number;
453
- } {
454
- return {
455
- size: this.size,
456
- capacity: this.capacity,
457
- isEmpty: this.isEmpty,
458
- isFull: this.isFull,
459
- isClosed: this._isClosed,
460
- waitingPutters: this.putters.length,
461
- waitingTakers: this.takers.length,
462
- remainingCapacity: this.remainingCapacity,
463
- };
464
- }
465
-
466
- toString(): string {
467
- return `AsyncQueue[size=${this.size}, capacity=${this.capacity}, closed=${this._isClosed}]`;
468
- }
469
- }
470
-
471
- /**
472
- * Factory function to create an AsyncQueue.
473
- *
474
- * @example
475
- * const queue = asyncQueue<number>({ capacity: 100 })
476
- * await queue.put(42)
477
- * const value = await queue.take()
478
- */
479
- export function asyncQueue<T>(options?: AsyncQueueOptions): AsyncQueue<T> {
480
- return new AsyncQueue<T>(options);
481
- }