evnty 3.0.40 → 4.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/build/index.d.ts CHANGED
@@ -25,6 +25,7 @@ export interface Expander<T, R> {
25
25
  * Removes a listener from the provided array of listeners. It searches for the listener and removes all instances of it from the array.
26
26
  * This method ensures that the listener is fully unregistered, preventing any residual calls to a potentially deprecated handler.
27
27
  *
28
+ * @internal
28
29
  * @param {Listener<T, R>[]} listeners - The array of listeners from which to remove the listener.
29
30
  * @param {Listener<T, R>} listener - The listener function to remove from the list of listeners.
30
31
  * @returns {boolean} - Returns `true` if the listener was found and removed, `false` otherwise.
@@ -32,20 +33,28 @@ export interface Expander<T, R> {
32
33
  * @template T - The type of the event that listeners are associated with.
33
34
  * @template R - The type of the return value that listeners are expected to return.
34
35
  *
35
- * @example
36
+ * ```typescript
36
37
  * // Assuming an array of listeners for click events
37
38
  * const listeners = [onClickHandler1, onClickHandler2];
38
39
  * const wasRemoved = removeListener(listeners, onClickHandler1);
39
40
  * console.log(wasRemoved); // Output: true
41
+ * ```
40
42
  */
41
43
  export declare const removeListener: <T, R>(listeners: Listener<T, R>[], listener: Listener<T, R>) => boolean;
44
+ /**
45
+ * @internal
46
+ * @param timeout
47
+ * @param signal
48
+ * @returns
49
+ */
50
+ export declare const setTimeoutAsync: (timeout: number, signal?: AbortSignal) => Promise<boolean>;
42
51
  /**
43
52
  * An abstract class that extends the built-in Function class. It allows instances of the class
44
- * to be called as functions. When an instance of FunctionExt is called as a function, it will
53
+ * to be called as functions. When an instance of Callable is called as a function, it will
45
54
  * call the function passed to its constructor with the same arguments.
46
55
  * @internal
47
56
  */
48
- export declare abstract class FunctionExt extends Function {
57
+ export declare abstract class Callable extends Function {
49
58
  constructor(func: Function);
50
59
  }
51
60
  export interface Unsubscribe {
@@ -54,126 +63,99 @@ export interface Unsubscribe {
54
63
  /**
55
64
  * @internal
56
65
  */
57
- export declare class Unsubscribe extends FunctionExt {
66
+ export declare class Unsubscribe extends Callable {
58
67
  constructor(callback: Callback);
59
68
  pre(callback: Callback): Unsubscribe;
60
69
  post(callback: Callback): Unsubscribe;
61
70
  countdown(count: number): Unsubscribe;
62
71
  }
63
- export interface Event<T = any, R = any> {
64
- (event: T): Promise<(void | Awaited<R>)[]>;
65
- }
66
- /**
67
- * Represents a pair of events handling both successful outcomes and errors.
68
- * This interface is used to manage asynchronous operations where events can either
69
- * result in a successful output or an error.
70
- *
71
- * The `value` event is triggered when the operation succeeds and emits a result.
72
- * The `error` event is triggered when the operation encounters an error, allowing
73
- * error handling mechanisms to process or log the error accordingly.
74
- *
75
- * @template T The type of data emitted by the successful outcome of the event.
76
- * @template R The type of data (if any) emitted by the error event.
77
- * @template E The type of error information emitted by the error event, usually an Error object or string.
78
- *
79
- * @example
80
- * // Assume an asynchronous function that fetches user data
81
- * function fetchUserData(): ResultEvents<UserData, Error> {
82
- * const success = new Event<UserData>();
83
- * const failure = new Event<Error>();
84
- *
85
- * fetch('/api/user')
86
- * .then(response => response.json())
87
- * .then(data => success(data))
88
- * .catch(error => failure(error));
89
- *
90
- * return { value: success, error: failure };
91
- * }
92
- *
93
- * const userDataEvent = fetchUserData();
94
- * userDataEvent.value.on(data => console.log('User data received:', data));
95
- * userDataEvent.error.on(error => console.error('An error occurred:', error));
96
- */
97
- export interface ResultEvents<T, R, E = unknown> {
98
- value: Event<T, R>;
99
- error: Event<E, void>;
100
- }
101
72
  export interface Queue<T> {
102
- pop(): MaybePromise<T | undefined>;
73
+ pop(): MaybePromise<T>;
103
74
  stop(): MaybePromise<void>;
104
75
  }
76
+ export interface Event<T = any, R = any> {
77
+ (event: T): Promise<(void | Awaited<R>)[]>;
78
+ }
105
79
  /**
106
80
  * A class representing an anonymous event that can be listened to or triggered.
107
81
  *
108
- * @typeParam T - The tuple of arguments that the event takes.
109
- * @typeParam R - The return type of the event.
82
+ * @template T - The event type.
83
+ * @template R - The return type of the event.
110
84
  */
111
- export declare class Event<T, R> extends FunctionExt {
85
+ export declare class Event<T, R> extends Callable implements AsyncIterable<T>, PromiseLike<T> {
112
86
  /**
113
87
  * The array of listeners for the event.
114
88
  */
115
89
  private listeners;
116
- /**
117
- * The array of listeners for the event.
118
- */
119
- private addSpies;
120
- private removeSpies;
90
+ private spies;
121
91
  /**
122
92
  * A function that disposes of the event and its listeners.
123
93
  */
124
94
  readonly dispose: Callback;
125
95
  /**
126
96
  * Creates a new event.
127
- * @example
97
+ *
98
+ * @param dispose - A function to call on the event disposal.
99
+ *
100
+ * ```typescript
128
101
  * // Create a click event.
129
102
  * const clickEvent = new Event<[x: number, y: number], void>();
130
103
  * clickEvent.on(([x, y]) => console.log(`Clicked at ${x}, ${y}`));
131
- *
132
- * @param dispose - A function to call on the event disposal.
104
+ * ```
133
105
  */
134
106
  constructor(dispose?: Callback);
107
+ private _error?;
108
+ /**
109
+ * Error event that emits errors.
110
+ *
111
+ * @returns {Event<unknown>} The error event.
112
+ */
113
+ get error(): Event<unknown>;
135
114
  /**
136
115
  * The number of listeners for the event.
116
+ *
117
+ * @readonly
118
+ * @type {number}
137
119
  */
138
120
  get size(): number;
139
121
  /**
140
- * Checks if a specific listener is not registered for the event.
141
- * This method is typically used to verify whether an event listener has not been added to prevent duplicate registrations.
122
+ * Checks if the given listener is NOT registered for this event.
123
+ *
142
124
  * @param listener - The listener function to check against the registered listeners.
143
125
  * @returns `true` if the listener is not already registered; otherwise, `false`.
144
126
  *
145
- * @example
127
+ * ```typescript
146
128
  * // Check if a listener is not already added
147
129
  * if (event.lacks(myListener)) {
148
130
  * event.on(myListener);
149
131
  * }
150
- *
132
+ * ```
151
133
  */
152
134
  lacks(listener: Listener<T, R>): boolean;
153
135
  /**
154
- * Checks if a specific listener is registered for the event.
155
- * This method is used to confirm the presence of a listener in the event's registration list.
136
+ * Checks if the given listener is registered for this event.
156
137
  *
157
- * @param listener - The listener function to verify.
138
+ * @param listener - The listener function to check.
158
139
  * @returns `true` if the listener is currently registered; otherwise, `false`.
159
140
  *
160
- * @example
141
+ * ```typescript
161
142
  * // Verify if a listener is registered
162
143
  * if (event.has(myListener)) {
163
144
  * console.log('Listener is already registered');
164
145
  * }
146
+ * ```
165
147
  */
166
148
  has(listener: Listener<T, R>): boolean;
167
149
  /**
168
- * Removes a listener from the event's registration list.
169
- * This method is used when the listener is no longer needed, helping to prevent memory leaks and unnecessary executions.
150
+ * Removes a specific listener from this event.
170
151
  *
171
152
  * @param listener - The listener to remove.
172
153
  * @returns The event instance, allowing for method chaining.
173
154
  *
174
- * @example
155
+ * ```typescript
175
156
  * // Remove a listener
176
157
  * event.off(myListener);
158
+ * ```
177
159
  */
178
160
  off(listener: Listener<T, R>): this;
179
161
  /**
@@ -183,11 +165,12 @@ export declare class Event<T, R> extends FunctionExt {
183
165
  * @param listener - The function to call when the event occurs.
184
166
  * @returns An object that can be used to unsubscribe the listener, ensuring easy cleanup.
185
167
  *
186
- * @example
168
+ * ```typescript
187
169
  * // Add a listener to an event
188
170
  * const unsubscribe = event.on((data) => {
189
171
  * console.log('Event data:', data);
190
172
  * });
173
+ * ```
191
174
  */
192
175
  on(listener: Listener<T, R>): Unsubscribe;
193
176
  /**
@@ -196,47 +179,124 @@ export declare class Event<T, R> extends FunctionExt {
196
179
  *
197
180
  * @param listener - The listener to trigger once.
198
181
  * @returns An object that can be used to remove the listener if the event has not yet occurred.
199
- * @example
182
+ *
183
+ * ```typescript
200
184
  * // Register a one-time listener
201
185
  * const onceUnsubscribe = event.once((data) => {
202
186
  * console.log('Received data once:', data);
203
187
  * });
188
+ * ```
204
189
  */
205
190
  once(listener: Listener<T, R>): Unsubscribe;
206
- /**
207
- * Returns a Promise that resolves with the first event argument emitted.
208
- * This method is useful for scenarios where you need to wait for the first occurrence
209
- * of an event and then perform actions based on the event data.
210
- *
211
- * @returns {Promise<T>} A Promise that resolves with the first event argument emitted.
212
- * @example
213
- * const clickEvent = new Event<[number, number]>();
214
- * clickEvent.onceAsync().then(([x, y]) => {
215
- * console.log(`First click at (${x}, ${y})`);
216
- * });
217
- */
218
- onceAsync(): Promise<T>;
219
191
  /**
220
192
  * Removes all listeners from the event, effectively resetting it. This is useful when you need to
221
193
  * cleanly dispose of all event handlers to prevent memory leaks or unwanted triggerings after certain conditions.
222
194
  *
223
195
  * @returns {this} The instance of the event, allowing for method chaining.
224
- * @example
196
+ *
197
+ * ```typescript
225
198
  * const myEvent = new Event();
226
199
  * myEvent.on(data => console.log(data));
227
200
  * myEvent.clear(); // Clears all listeners
201
+ * ```
228
202
  */
229
203
  clear(): this;
204
+ /**
205
+ * Enables the `Event` to be used in a Promise chain, resolving with the first emitted value.
206
+ *
207
+ * @template TResult1 - The type of the fulfilled value returned by `onfulfilled` (defaults to the event's type).
208
+ * @template TResult2 - The type of the rejected value returned by `onrejected` (defaults to `never`).
209
+ * @param onfulfilled - A function called when the event emits its first value.
210
+ * @param onrejected - A function called if an error occurs before the event emits.
211
+ * @returns A Promise that resolves with the result of `onfulfilled` or `onrejected`.
212
+ *
213
+ * ```typescript
214
+ * const clickEvent = new Event<[number, number]>();
215
+ * await clickEvent;
216
+ * ```
217
+ */
218
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
219
+ /**
220
+ * A promise that resolves with the first emitted value from this event.
221
+ *
222
+ * @returns {Promise<T>} The promise value.
223
+ */
224
+ get promise(): Promise<T>;
225
+ /**
226
+ * Makes this event iterable using `for await...of` loops.
227
+ *
228
+ * @returns An async iterator that yields values as they are emitted by this event.
229
+ *
230
+ * ```typescript
231
+ * // Assuming an event that emits numbers
232
+ * const numberEvent = new Event<number>();
233
+ * (async () => {
234
+ * for await (const num of numberEvent) {
235
+ * console.log('Number:', num);
236
+ * }
237
+ * })();
238
+ * await numberEvent(1);
239
+ * await numberEvent(2);
240
+ * await numberEvent(3);
241
+ * ```
242
+ */
243
+ [Symbol.asyncIterator](): AsyncIterator<T>;
244
+ /**
245
+ * Transforms the event's values using a generator function, creating a new `Event` that emits the transformed values.
246
+ *
247
+ * @template PT - The type of values emitted by the transformed `Event`.
248
+ * @template PR - The return type of the listeners of the transformed `Event`.
249
+ * @param generator - A function that takes the original event's value and returns a generator (sync or async) that yields the transformed values.
250
+ * @returns A new `Event` instance that emits the transformed values.
251
+ *
252
+ * ```typescript
253
+ * const numbersEvent = new Event<number>();
254
+ * const evenNumbersEvent = numbersEvent.pipe(function*(value) {
255
+ * if (value % 2 === 0) {
256
+ * yield value;
257
+ * }
258
+ * });
259
+ * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));
260
+ * await numbersEvent(1);
261
+ * await numbersEvent(2);
262
+ * await numbersEvent(3);
263
+ * ```
264
+ */
265
+ pipe<PT, R>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): Event<PT, R>;
266
+ /**
267
+ * Creates an async generator that yields values as they are emitted by this event.
268
+ *
269
+ * @template PT - The type of values yielded by the async generator.
270
+ * @param generator - An optional function that takes the original event's value and returns a generator (sync or async)
271
+ * that yields values to include in the async generator.
272
+ * @returns An async generator that yields values from this event as they occur.
273
+ *
274
+ * ```typescript
275
+ * const numbersEvent = new Event<number>();
276
+ * const evenNumbersEvent = numbersEvent.pipe(function*(value) {
277
+ * if (value % 2 === 0) {
278
+ * yield value;
279
+ * }
280
+ * });
281
+ * evenNumbersEvent.on((evenNumber) => console.log(evenNumber));
282
+ * await numbersEvent(1);
283
+ * await numbersEvent(2);
284
+ * await numbersEvent(3);
285
+ * ```
286
+ */
287
+ generator<PT>(generator: (event: T) => AsyncGenerator<PT, void, unknown> | Generator<PT, void, unknown>): AsyncGenerator<Awaited<PT>, void, unknown>;
230
288
  /**
231
289
  * Filters events, creating a new event that only triggers when the provided filter function returns `true`.
232
290
  * This method can be used to selectively process events that meet certain criteria.
233
291
  *
234
- * @param {Filter<T, P>} filter The filter function or predicate to apply to each event.
292
+ * @param {Filter<T, P>} predicate The filter function or predicate to apply to each event.
235
293
  * @returns {Event<P, R>} A new event that only triggers for filtered events.
236
- * @example
294
+ *
295
+ * ```typescript
237
296
  * const keyPressedEvent = new Event<string>();
238
297
  * const enterPressedEvent = keyPressedEvent.filter(key => key === 'Enter');
239
298
  * enterPressedEvent.on(() => console.log('Enter key was pressed.'));
299
+ * ```
240
300
  */
241
301
  filter<P extends T>(predicate: Predicate<T, P>): Event<P, R>;
242
302
  filter<P extends T>(filter: FilterFunction<T>): Event<P, R>;
@@ -244,28 +304,17 @@ export declare class Event<T, R> extends FunctionExt {
244
304
  * Creates a new event that will only be triggered once when the provided filter function returns `true`.
245
305
  * This method is useful for handling one-time conditions in a stream of events.
246
306
  *
247
- * @param {Filter<T, P>} filter - The filter function or predicate.
307
+ * @param {Filter<T, P>} predicate - The filter function or predicate.
248
308
  * @returns {Event<P, R>} A new event that will be triggered only once when the filter condition is met.
249
- * @example
309
+ *
310
+ * ```typescript
250
311
  * const sizeChangeEvent = new Event<number>();
251
312
  * const sizeReachedEvent = sizeChangeEvent.first(size => size > 1024);
252
313
  * sizeReachedEvent.on(() => console.log('Size threshold exceeded.'));
314
+ * ```
253
315
  */
254
316
  first<P extends T>(predicate: Predicate<T, P>): Event<P, R>;
255
317
  first<P extends T>(filter: FilterFunction<T>): Event<P, R>;
256
- /**
257
- * Returns a Promise that resolves once an event occurs that meets the filter criteria.
258
- * This method is particularly useful for handling asynchronous flows where you need to wait for a specific condition.
259
- *
260
- * @param {Filter<T, P>} filter - The filter function or predicate.
261
- * @returns {Promise<P>} A Promise that resolves once the filter condition is met.
262
- * @example
263
- * const mouseEvent = new Event<{x: number, y: number}>();
264
- * const clickAtPosition = mouseEvent.firstAsync(pos => pos.x > 200 && pos.y > 200);
265
- * clickAtPosition.then(pos => console.log(`Clicked at (${pos.x}, ${pos.y})`));
266
- */
267
- firstAsync<P extends T>(predicate: Predicate<T, P>): Promise<P>;
268
- firstAsync<P extends T>(filter: FilterFunction<T>): Promise<P>;
269
318
  /**
270
319
  * Transforms the data emitted by this event using a mapping function. Each emitted event is processed by the `mapper`
271
320
  * function, which returns a new value that is then emitted by the returned `Event` instance. This is useful for data transformation
@@ -276,37 +325,35 @@ export declare class Event<T, R> extends FunctionExt {
276
325
  * @param {Mapper<T, M>} mapper A function that takes the original event data and returns the transformed data.
277
326
  * @returns {Event<M, MR>} A new `Event` instance that emits the mapped values.
278
327
  *
279
- * @example
328
+ * ```typescript
280
329
  * // Assuming an event that emits numbers, create a new event that emits their squares.
281
330
  * const numberEvent = new Event<number>();
282
331
  * const squaredEvent = numberEvent.map(num => num * num);
283
332
  * squaredEvent.on(squared => console.log('Squared number:', squared));
284
333
  * await numberEvent(5); // Logs: "Squared number: 25"
285
- *
286
- * @param mapper A function that maps the values of this event to a new value.
287
- * @returns A new event that emits the mapped values.
334
+ * ```
288
335
  */
289
- map<M, MR = R>(mapper: Mapper<T, M>): Event<M, MR>;
336
+ map<M, MR = R>(mapper: Mapper<T, M>): Event<Awaited<M>, MR>;
290
337
  /**
291
338
  * Accumulates the values emitted by this event using a reducer function, starting from an initial value. The reducer
292
339
  * function takes the accumulated value and the latest emitted event data, then returns a new accumulated value. This
293
340
  * new value is then emitted by the returned `Event` instance. This is particularly useful for accumulating state over time.
294
341
  *
295
- * @example
296
- * const sumEvent = numberEvent.reduce((a, b) => a + b, 0);
297
- * sumEvent.on((sum) => console.log(sum)); // 1, 3, 6
298
- * await sumEvent(1);
299
- * await sumEvent(2);
300
- * await sumEvent(3);
301
- *
302
342
  * @template A The type of the accumulator value.
303
343
  * @template AR The type of data emitted by the reduced event, usually the same as `A`.
304
344
  * @param {Reducer<T, A>} reducer A function that takes the current accumulated value and the new event data, returning the new accumulated value.
305
345
  * @param {A} init The initial value of the accumulator.
306
346
  * @returns {Event<A, AR>} A new `Event` instance that emits the reduced value.
307
347
  *
348
+ * ```typescript
349
+ * const sumEvent = numberEvent.reduce((a, b) => a + b, 0);
350
+ * sumEvent.on((sum) => console.log(sum)); // 1, 3, 6
351
+ * await sumEvent(1);
352
+ * await sumEvent(2);
353
+ * await sumEvent(3);
354
+ * ```
308
355
  */
309
- reduce<A, AR = R>(reducer: Reducer<T, A>, init: A): Event<A, AR>;
356
+ reduce<A, AR = R>(reducer: Reducer<T, A>, init?: A): Event<Awaited<A>, AR>;
310
357
  /**
311
358
  * Transforms each event's data into multiple events using an expander function. The expander function takes
312
359
  * the original event's data and returns an array of new data elements, each of which will be emitted individually
@@ -318,23 +365,30 @@ export declare class Event<T, R> extends FunctionExt {
318
365
  * @param {Expander<T, ET[]>} expander - A function that takes the original event data and returns an array of new data elements.
319
366
  * @returns {Event<ET, ER>} - A new `Event` instance that emits each value from the array returned by the expander function.
320
367
  *
321
- * @example
368
+ * ```typescript
322
369
  * // Assuming an event that emits a sentence, create a new event that emits each word from the sentence separately.
323
370
  * const sentenceEvent = new Event<string>();
324
371
  * const wordEvent = sentenceEvent.expand(sentence => sentence.split(' '));
325
372
  * wordEvent.on(word => console.log('Word:', word));
326
373
  * await sentenceEvent('Hello world'); // Logs: "Word: Hello", "Word: world"
374
+ * ```
327
375
  */
328
- expand<ET, ER>(expander: Expander<T, ET[]>): Event<ET, ER>;
376
+ expand<ET, ER>(expander: Expander<T, ET[]>): Event<Awaited<ET>, ER>;
329
377
  /**
330
378
  * Creates a new event that emits values based on a conductor event. The orchestrated event will emit the last value
331
379
  * captured from the original event each time the conductor event is triggered. This method is useful for synchronizing
332
380
  * events, where the emission of one event controls the timing of another.
333
381
  *
334
- * @example
382
+ * @template T The type of data emitted by the original event.
383
+ * @template R The type of data emitted by the orchestrated event, usually the same as `T`.
384
+ * @param {Event<unknown, unknown>} conductor An event that signals when the orchestrated event should emit.
385
+ * @returns {Event<T, R>} An orchestrated event that emits values based on the conductor's trigger.
386
+ *
387
+ * ```typescript
335
388
  * const rightClickPositionEvent = mouseMoveEvent.orchestrate(mouseRightClickEvent);
389
+ * ```
336
390
  *
337
- * @example
391
+ * ```typescript
338
392
  * // An event that emits whenever a "tick" event occurs.
339
393
  * const tickEvent = new Event<void>();
340
394
  * const dataEvent = new Event<string>();
@@ -343,12 +397,7 @@ export declare class Event<T, R> extends FunctionExt {
343
397
  * await dataEvent('Hello');
344
398
  * await dataEvent('World!');
345
399
  * await tickEvent(); // Logs: "Data on tick: World!"
346
- *
347
- * @template T The type of data emitted by the original event.
348
- * @template R The type of data emitted by the orchestrated event, usually the same as `T`.
349
- * @param {Event<unknown, unknown>} conductor An event that signals when the orchestrated event should emit.
350
- * @returns {Event<T, R>} An orchestrated event that emits values based on the conductor's trigger.
351
- *
400
+ * ```
352
401
  */
353
402
  orchestrate(conductor: Event<any, any>): Event<T, R>;
354
403
  /**
@@ -357,72 +406,71 @@ export declare class Event<T, R> extends FunctionExt {
357
406
  * at which a function is executed. Common use cases include handling rapid user inputs, window resizing,
358
407
  * or scroll events.
359
408
  *
360
- * @example
409
+ * @param {number} interval - The amount of time to wait (in milliseconds) before firing the debounced event.
410
+ * @returns {Event<T, R>} An event of debounced events.
411
+ *
412
+ * ```typescript
361
413
  * const debouncedEvent = textInputEvent.debounce(100);
362
414
  * debouncedEvent.on((str) => console.log(str)); // only 'text' is emitted
363
415
  * await event('t');
364
416
  * await event('te');
365
417
  * await event('tex');
366
418
  * await event('text');
419
+ * ```
420
+ */
421
+ debounce(interval: number): Event<Awaited<T>, unknown>;
422
+ /**
423
+ * Creates a throttled event that emits values at most once per specified interval.
367
424
  *
368
- * @param {number} interval - The amount of time to wait (in milliseconds) before firing the debounced event.
369
- * @returns {ResultEvents<T, R, unknown>} An object containing two events: `value` for the debounced successful
370
- * outputs and `error` for catching errors during the debounce handling.
425
+ * This is useful for controlling the rate of event emissions, especially for high-frequency events.
426
+ * The throttled event will immediately emit the first value, and then only emit subsequent values
427
+ * if the specified interval has passed since the last emission.
428
+ *
429
+ * @param interval - The time interval (in milliseconds) between allowed emissions.
430
+ * @returns A new Event that emits throttled values.
431
+ *
432
+ * ```typescript
433
+ * const scrollEvent = new Event();
434
+ * const throttledScroll = scrollEvent.throttle(100); // Emit at most every 100ms
435
+ * throttledScroll.on(() => console.log("Throttled scroll event"));
436
+ * ```
371
437
  */
372
- debounce(interval: number): ResultEvents<T, R, unknown>;
438
+ throttle(interval: number): Event<Awaited<T>, unknown>;
373
439
  /**
374
440
  * Aggregates multiple event emissions into batches and emits the batched events either at specified
375
441
  * time intervals or when the batch reaches a predefined size. This method is useful for grouping
376
442
  * a high volume of events into manageable chunks, such as logging or processing data in bulk.
377
443
  *
378
- * @example
379
- * // Batch messages for bulk processing every 1 second or when 10 messages are collected
380
- * const messageEvent = createEvent<string, void>();
381
- * const batchedMessageEvent = messageEvent.batch(1000, 10);
382
- * batchedMessageEvent.value.on((messages) => console.log('Batched Messages:', messages));
383
- *
384
444
  * @param {number} interval - The time in milliseconds between batch emissions.
385
445
  * @param {number} [size] - Optional. The maximum size of each batch. If specified, triggers a batch emission
386
446
  * once the batch reaches this size, regardless of the interval.
387
- * @returns {ResultEvents<T[], R, unknown>} An object containing two events: `value` for the batched results
388
- * and `error` for errors that may occur during batching.
389
- */
390
- batch(interval: number, size?: number): ResultEvents<T[], R, unknown>;
391
- /**
392
- * Transforms an event into an AsyncIterable that yields values as they are emitted by the event. This allows for the consumption
393
- * of event data using async iteration mechanisms. The iterator generated will yield all emitted values until the event
394
- * signals it should no longer be active.
447
+ * @returns {Event<T[], R>} An event of the batched results.
395
448
  *
396
- * @returns {AsyncIterable<T>} An async iterable that yields values emitted by the event.
397
- * @example
398
- * // Assuming an event that emits numbers
399
- * const numberEvent = new Event<number>();
400
- * const numberIterable = numberEvent.generator();
401
- * (async () => {
402
- * for await (const num of numberIterable) {
403
- * console.log('Number:', num);
404
- * }
405
- * })();
406
- * await numberEvent(1);
407
- * await numberEvent(2);
408
- * await numberEvent(3);
449
+ * ```typescript
450
+ * // Batch messages for bulk processing every 1 second or when 10 messages are collected
451
+ * const messageEvent = createEvent<string, void>();
452
+ * const batchedMessageEvent = messageEvent.batch(1000, 10);
453
+ * batchedMessageEvent.on((messages) => console.log('Batched Messages:', messages));
454
+ * ```
409
455
  */
410
- generator(): AsyncIterable<T>;
456
+ batch(interval: number, size?: number): Event<T[], R>;
411
457
  /**
412
458
  * Creates a queue from the event, where each emitted value is sequentially processed. The returned object allows popping elements
413
459
  * from the queue, ensuring that elements are handled one at a time. This method is ideal for scenarios where order and sequential processing are critical.
414
460
  *
415
461
  * @returns {Queue<T>} An object representing the queue. The 'pop' method retrieves the next element from the queue, while 'stop' halts further processing.
416
- * @example
462
+ *
463
+ * ```typescript
417
464
  * // Queueing tasks for sequential execution
418
465
  * const taskEvent = new Event<string>();
419
466
  * const taskQueue = taskEvent.queue();
420
- * await taskEvent('Task 1');
421
- * await taskEvent('Task 2');
422
467
  * (async () => {
423
468
  * console.log('Processing:', await taskQueue.pop()); // Processing: Task 1
424
469
  * console.log('Processing:', await taskQueue.pop()); // Processing: Task 2
425
470
  * })();
471
+ * await taskEvent('Task 1');
472
+ * await taskEvent('Task 2');
473
+ * ```
426
474
  */
427
475
  queue(): Queue<T>;
428
476
  }
@@ -445,12 +493,13 @@ export type AllEventsResults<T extends Event<any, any>[]> = {
445
493
  * @returns {Event<AllEventsParameters<Events>, AllEventsResults<Events>>} - Returns a new `Event` instance
446
494
  * that triggers with the parameters and results of any of the merged input events.
447
495
  *
448
- * @example
496
+ * ```typescript
449
497
  * // Merging mouse and keyboard events into a single event
450
498
  * const mouseEvent = createEvent<MouseEvent>();
451
499
  * const keyboardEvent = createEvent<KeyboardEvent>();
452
500
  * const inputEvent = merge(mouseEvent, keyboardEvent);
453
501
  * inputEvent.on(event => console.log('Input event:', event));
502
+ * ```
454
503
  */
455
504
  export declare const merge: <Events extends Event<any, any>[]>(...events: Events) => Event<AllEventsParameters<Events>, AllEventsResults<Events>>;
456
505
  /**
@@ -464,10 +513,11 @@ export declare const merge: <Events extends Event<any, any>[]>(...events: Events
464
513
  * @returns {Event<number, R>} - An `Event` instance that triggers at the specified interval,
465
514
  * emitting an incrementing counter value.
466
515
  *
467
- * @example
516
+ * ```typescript
468
517
  * // Creating an interval event that logs a message every second
469
518
  * const tickEvent = createInterval(1000);
470
519
  * tickEvent.on(tickNumber => console.log('Tick:', tickNumber));
520
+ * ```
471
521
  */
472
522
  export declare const createInterval: <R = void>(interval: number) => Event<number, R>;
473
523
  /**
@@ -478,13 +528,14 @@ export declare const createInterval: <R = void>(interval: number) => Event<numbe
478
528
  * @typeParam R - The return type of the event handler function, which is emitted after processing the event data.
479
529
  * @returns {Event<T, R>} - A new instance of the `Event` class, ready to have listeners added to it.
480
530
  *
481
- * @example
531
+ * ```typescript
482
532
  * // Create a new event that accepts a string and returns the string length
483
533
  * const myEvent = createEvent<string, number>();
484
534
  * myEvent.on((str: string) => str.length);
485
535
  * myEvent('hello').then(results => console.log(results)); // Logs: [5]
536
+ * ```
486
537
  */
487
- export declare const createEvent: <T, R = void>() => Event<T, R>;
538
+ export declare const createEvent: <T = unknown, R = unknown>() => Event<T, R>;
488
539
  export default createEvent;
489
540
  /**
490
541
  * A type helper that extracts the event listener type