@tanstack/pacer 0.6.0 → 0.8.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/dist/cjs/async-debouncer.cjs +10 -6
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +2 -2
- package/dist/cjs/async-queuer.cjs +140 -111
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +121 -93
- package/dist/cjs/async-rate-limiter.cjs +3 -4
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +1 -2
- package/dist/cjs/async-throttler.cjs +14 -4
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +3 -2
- package/dist/cjs/batcher.cjs +138 -0
- package/dist/cjs/batcher.cjs.map +1 -0
- package/dist/cjs/batcher.d.cts +149 -0
- package/dist/cjs/debouncer.cjs +3 -4
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +1 -2
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +1 -0
- package/dist/cjs/queuer.cjs +70 -43
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +126 -95
- package/dist/cjs/rate-limiter.cjs +3 -4
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +1 -2
- package/dist/cjs/throttler.cjs +3 -4
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +1 -2
- package/dist/esm/async-debouncer.d.ts +2 -2
- package/dist/esm/async-debouncer.js +10 -6
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +121 -93
- package/dist/esm/async-queuer.js +140 -111
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +1 -2
- package/dist/esm/async-rate-limiter.js +3 -4
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +3 -2
- package/dist/esm/async-throttler.js +14 -4
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/batcher.d.ts +149 -0
- package/dist/esm/batcher.js +138 -0
- package/dist/esm/batcher.js.map +1 -0
- package/dist/esm/debouncer.d.ts +1 -2
- package/dist/esm/debouncer.js +3 -4
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/queuer.d.ts +126 -95
- package/dist/esm/queuer.js +70 -43
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +1 -2
- package/dist/esm/rate-limiter.js +3 -4
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +1 -2
- package/dist/esm/throttler.js +3 -4
- package/dist/esm/throttler.js.map +1 -1
- package/package.json +11 -1
- package/src/async-debouncer.ts +12 -6
- package/src/async-queuer.ts +217 -194
- package/src/async-rate-limiter.ts +3 -4
- package/src/async-throttler.ts +18 -4
- package/src/batcher.ts +253 -0
- package/src/debouncer.ts +3 -4
- package/src/index.ts +1 -0
- package/src/queuer.ts +145 -101
- package/src/rate-limiter.ts +3 -4
- package/src/throttler.ts +3 -4
package/dist/cjs/queuer.d.cts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Options for configuring a Queuer instance
|
|
2
|
+
* Options for configuring a Queuer instance.
|
|
3
|
+
*
|
|
4
|
+
* These options control queue behavior, item expiration, callbacks, and more.
|
|
3
5
|
*/
|
|
4
6
|
export interface QueuerOptions<TValue> {
|
|
5
7
|
/**
|
|
@@ -42,7 +44,7 @@ export interface QueuerOptions<TValue> {
|
|
|
42
44
|
/**
|
|
43
45
|
* Callback fired whenever an item is removed from the queuer
|
|
44
46
|
*/
|
|
45
|
-
|
|
47
|
+
onExecute?: (item: TValue, queuer: Queuer<TValue>) => void;
|
|
46
48
|
/**
|
|
47
49
|
* Callback fired whenever the queuer's running state changes
|
|
48
50
|
*/
|
|
@@ -67,64 +69,75 @@ export interface QueuerOptions<TValue> {
|
|
|
67
69
|
wait?: number | ((queuer: Queuer<TValue>) => number);
|
|
68
70
|
}
|
|
69
71
|
/**
|
|
70
|
-
* Position type for addItem and getNextItem operations
|
|
72
|
+
* Position type for addItem and getNextItem operations.
|
|
73
|
+
*
|
|
74
|
+
* - 'front': Operate on the front of the queue (FIFO)
|
|
75
|
+
* - 'back': Operate on the back of the queue (LIFO)
|
|
71
76
|
*/
|
|
72
77
|
export type QueuePosition = 'front' | 'back';
|
|
73
78
|
/**
|
|
74
|
-
* A flexible queue
|
|
75
|
-
* with optional position overrides for stack-like or double-ended operations.
|
|
79
|
+
* A flexible queue that processes items with configurable wait times, expiration, and priority.
|
|
76
80
|
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
81
|
+
* Features:
|
|
82
|
+
* - Automatic or manual processing of items
|
|
83
|
+
* - FIFO (First In First Out), LIFO (Last In First Out), or double-ended queue behavior
|
|
84
|
+
* - Priority-based ordering when getPriority is provided
|
|
85
|
+
* - Item expiration and removal of stale items
|
|
86
|
+
* - Callbacks for queue state changes, execution, rejection, and expiration
|
|
80
87
|
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
88
|
+
* Running behavior:
|
|
89
|
+
* - `start()`: Begins automatically processing items in the queue (defaults to running)
|
|
90
|
+
* - `stop()`: Pauses processing but maintains queue state
|
|
91
|
+
* - `wait`: Configurable delay between processing items
|
|
92
|
+
* - `onItemsChange`/`onExecute`: Callbacks for monitoring queue state
|
|
83
93
|
*
|
|
84
|
-
*
|
|
85
|
-
* -
|
|
86
|
-
* - getNextItem()
|
|
94
|
+
* Manual processing is also supported when automatic processing is disabled:
|
|
95
|
+
* - `execute()`: Processes the next item using the provided function
|
|
96
|
+
* - `getNextItem()`: Removes and returns the next item without processing
|
|
87
97
|
*
|
|
88
|
-
*
|
|
89
|
-
* - addItem(item
|
|
90
|
-
* -
|
|
98
|
+
* Queue behavior defaults to FIFO:
|
|
99
|
+
* - `addItem(item)`: Adds to the back of the queue
|
|
100
|
+
* - Items processed from the front of the queue
|
|
91
101
|
*
|
|
92
|
-
*
|
|
93
|
-
* -
|
|
94
|
-
* - getNextItem(position): removes and returns from specified position
|
|
102
|
+
* Priority queue:
|
|
103
|
+
* - Provide a `getPriority` function; higher values are processed first
|
|
95
104
|
*
|
|
96
|
-
*
|
|
97
|
-
* -
|
|
98
|
-
* -
|
|
99
|
-
* - wait: configurable delay between processing items
|
|
100
|
-
* - onItemsChange/onGetNextItem: callbacks for monitoring queuer state
|
|
105
|
+
* Stack (LIFO):
|
|
106
|
+
* - `addItem(item, 'back')`: Adds to the back
|
|
107
|
+
* - `getNextItem('back')`: Removes from the back
|
|
101
108
|
*
|
|
102
|
-
*
|
|
103
|
-
* -
|
|
104
|
-
* -
|
|
105
|
-
* - onExpire: callback for when an item expires
|
|
109
|
+
* Double-ended queue:
|
|
110
|
+
* - `addItem(item, position)`: Adds to specified position ('front'/'back')
|
|
111
|
+
* - `getNextItem(position)`: Removes from specified position
|
|
106
112
|
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
* queuer.addItem(1); // [1]
|
|
112
|
-
* queuer.addItem(2); // [1, 2]
|
|
113
|
-
* queuer.getNextItem(); // returns 1, queuer is [2]
|
|
113
|
+
* Item expiration:
|
|
114
|
+
* - `expirationDuration`: Maximum time items can stay in the queue
|
|
115
|
+
* - `getIsExpired`: Function to override default expiration
|
|
116
|
+
* - `onExpire`: Callback for expired items
|
|
114
117
|
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
+
* Example usage:
|
|
119
|
+
* ```ts
|
|
120
|
+
* // Auto-processing queue with wait time
|
|
121
|
+
* const autoQueue = new Queuer<number>((n) => console.log(n), {
|
|
118
122
|
* started: true, // Begin processing immediately
|
|
119
123
|
* wait: 1000, // Wait 1s between items
|
|
120
|
-
*
|
|
124
|
+
* onExecute: (item) => console.log(`Processed ${item}`)
|
|
121
125
|
* });
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
126
|
+
* autoQueue.addItem(1); // Will process after 1s
|
|
127
|
+
* autoQueue.addItem(2); // Will process 1s after first item
|
|
128
|
+
*
|
|
129
|
+
* // Manual processing queue
|
|
130
|
+
* const manualQueue = new Queuer<number>((n) => console.log(n), {
|
|
131
|
+
* started: false
|
|
132
|
+
* });
|
|
133
|
+
* manualQueue.addItem(1); // [1]
|
|
134
|
+
* manualQueue.addItem(2); // [1, 2]
|
|
135
|
+
* manualQueue.execute(); // logs 1, queue is [2]
|
|
136
|
+
* manualQueue.getNextItem(); // returns 2, queue is empty
|
|
125
137
|
* ```
|
|
126
138
|
*/
|
|
127
139
|
export declare class Queuer<TValue> {
|
|
140
|
+
private fn;
|
|
128
141
|
private _options;
|
|
129
142
|
private _items;
|
|
130
143
|
private _itemTimestamps;
|
|
@@ -134,136 +147,154 @@ export declare class Queuer<TValue> {
|
|
|
134
147
|
private _onItemsChanges;
|
|
135
148
|
private _running;
|
|
136
149
|
private _pendingTick;
|
|
137
|
-
constructor(initialOptions?: QueuerOptions<TValue>);
|
|
150
|
+
constructor(fn: (item: TValue) => void, initialOptions?: QueuerOptions<TValue>);
|
|
138
151
|
/**
|
|
139
|
-
* Updates the queuer options
|
|
140
|
-
* Returns the new options state
|
|
152
|
+
* Updates the queuer options. New options are merged with existing options.
|
|
141
153
|
*/
|
|
142
154
|
setOptions(newOptions: Partial<QueuerOptions<TValue>>): void;
|
|
143
155
|
/**
|
|
144
|
-
* Returns the current queuer options
|
|
156
|
+
* Returns the current queuer options, including defaults and any overrides.
|
|
145
157
|
*/
|
|
146
158
|
getOptions(): Required<QueuerOptions<TValue>>;
|
|
147
159
|
/**
|
|
148
|
-
* Returns the current wait time in milliseconds
|
|
160
|
+
* Returns the current wait time (in milliseconds) between processing items.
|
|
161
|
+
* If a function is provided, it is called with the queuer instance.
|
|
149
162
|
*/
|
|
150
163
|
getWait(): number;
|
|
151
164
|
/**
|
|
152
|
-
* Processes items in the
|
|
165
|
+
* Processes items in the queue up to the wait interval. Internal use only.
|
|
153
166
|
*/
|
|
154
167
|
private tick;
|
|
155
168
|
/**
|
|
156
|
-
* Checks for and removes
|
|
169
|
+
* Checks for expired items in the queue and removes them. Calls onExpire for each expired item.
|
|
170
|
+
* Internal use only.
|
|
157
171
|
*/
|
|
158
172
|
private checkExpiredItems;
|
|
159
173
|
/**
|
|
160
|
-
* Stops the
|
|
174
|
+
* Stops processing items in the queue. Does not clear the queue.
|
|
161
175
|
*/
|
|
162
176
|
stop(): void;
|
|
163
177
|
/**
|
|
164
|
-
* Starts the
|
|
178
|
+
* Starts processing items in the queue. If already running, does nothing.
|
|
165
179
|
*/
|
|
166
180
|
start(): void;
|
|
167
181
|
/**
|
|
168
|
-
* Removes all items from the
|
|
182
|
+
* Removes all pending items from the queue. Does not affect items being processed.
|
|
169
183
|
*/
|
|
170
184
|
clear(): void;
|
|
171
185
|
/**
|
|
172
|
-
* Resets the queuer to its initial state
|
|
186
|
+
* Resets the queuer to its initial state. Optionally repopulates with initial items.
|
|
187
|
+
* Does not affect callbacks or options.
|
|
173
188
|
*/
|
|
174
189
|
reset(withInitialItems?: boolean): void;
|
|
175
190
|
/**
|
|
176
|
-
* Adds an item to the
|
|
177
|
-
*
|
|
191
|
+
* Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.
|
|
192
|
+
* Items can be inserted based on priority or at the front/back depending on configuration.
|
|
193
|
+
*
|
|
194
|
+
* Returns true if the item was added, false if the queue is full.
|
|
195
|
+
*
|
|
196
|
+
* Example usage:
|
|
197
|
+
* ```ts
|
|
198
|
+
* queuer.addItem('task');
|
|
199
|
+
* queuer.addItem('task2', 'front');
|
|
200
|
+
* ```
|
|
178
201
|
*/
|
|
179
202
|
addItem(item: TValue, position?: QueuePosition, runOnUpdate?: boolean): boolean;
|
|
180
203
|
/**
|
|
181
|
-
* Removes and returns
|
|
204
|
+
* Removes and returns the next item from the queue without executing the function.
|
|
205
|
+
* Use for manual queue management. Normally, use execute() to process items.
|
|
182
206
|
*
|
|
183
|
-
*
|
|
207
|
+
* Example usage:
|
|
184
208
|
* ```ts
|
|
185
|
-
* //
|
|
186
|
-
* queuer.getNextItem()
|
|
187
|
-
* //
|
|
188
|
-
* queuer.getNextItem('back')
|
|
209
|
+
* // FIFO
|
|
210
|
+
* queuer.getNextItem();
|
|
211
|
+
* // LIFO
|
|
212
|
+
* queuer.getNextItem('back');
|
|
189
213
|
* ```
|
|
190
214
|
*/
|
|
191
215
|
getNextItem(position?: QueuePosition): TValue | undefined;
|
|
192
216
|
/**
|
|
193
|
-
*
|
|
217
|
+
* Removes and returns the next item from the queue and processes it using the provided function.
|
|
218
|
+
*
|
|
219
|
+
* Example usage:
|
|
220
|
+
* ```ts
|
|
221
|
+
* queuer.execute();
|
|
222
|
+
* // LIFO
|
|
223
|
+
* queuer.execute('back');
|
|
224
|
+
* ```
|
|
225
|
+
*/
|
|
226
|
+
execute(position?: QueuePosition): TValue | undefined;
|
|
227
|
+
/**
|
|
228
|
+
* Returns the next item in the queue without removing it.
|
|
194
229
|
*
|
|
195
|
-
*
|
|
230
|
+
* Example usage:
|
|
196
231
|
* ```ts
|
|
197
|
-
* //
|
|
198
|
-
* queuer.
|
|
199
|
-
* // Look at last item (like stack top)
|
|
200
|
-
* queuer.getPeek('back')
|
|
232
|
+
* queuer.peekNextItem(); // front
|
|
233
|
+
* queuer.peekNextItem('back'); // back
|
|
201
234
|
* ```
|
|
202
235
|
*/
|
|
203
|
-
|
|
236
|
+
peekNextItem(position?: QueuePosition): TValue | undefined;
|
|
204
237
|
/**
|
|
205
|
-
* Returns true if the
|
|
238
|
+
* Returns true if the queue is empty (no pending items).
|
|
206
239
|
*/
|
|
207
240
|
getIsEmpty(): boolean;
|
|
208
241
|
/**
|
|
209
|
-
* Returns true if the
|
|
242
|
+
* Returns true if the queue is full (reached maxSize).
|
|
210
243
|
*/
|
|
211
244
|
getIsFull(): boolean;
|
|
212
245
|
/**
|
|
213
|
-
* Returns the
|
|
246
|
+
* Returns the number of pending items in the queue.
|
|
214
247
|
*/
|
|
215
248
|
getSize(): number;
|
|
216
249
|
/**
|
|
217
|
-
* Returns a copy of all items in the
|
|
250
|
+
* Returns a copy of all items in the queue.
|
|
218
251
|
*/
|
|
219
|
-
|
|
252
|
+
peekAllItems(): Array<TValue>;
|
|
220
253
|
/**
|
|
221
|
-
* Returns the number of items that have been removed from the
|
|
254
|
+
* Returns the number of items that have been processed and removed from the queue.
|
|
222
255
|
*/
|
|
223
256
|
getExecutionCount(): number;
|
|
224
257
|
/**
|
|
225
|
-
* Returns the number of items that have been rejected from the
|
|
258
|
+
* Returns the number of items that have been rejected from being added to the queue.
|
|
226
259
|
*/
|
|
227
260
|
getRejectionCount(): number;
|
|
228
261
|
/**
|
|
229
|
-
* Returns the number of items that have expired from the
|
|
262
|
+
* Returns the number of items that have expired and been removed from the queue.
|
|
230
263
|
*/
|
|
231
264
|
getExpirationCount(): number;
|
|
232
265
|
/**
|
|
233
|
-
* Returns true if the queuer is running
|
|
266
|
+
* Returns true if the queuer is currently running (processing items).
|
|
234
267
|
*/
|
|
235
268
|
getIsRunning(): boolean;
|
|
236
269
|
/**
|
|
237
|
-
* Returns true if the queuer is running but has no items to process
|
|
270
|
+
* Returns true if the queuer is running but has no items to process.
|
|
238
271
|
*/
|
|
239
272
|
getIsIdle(): boolean;
|
|
240
273
|
}
|
|
241
274
|
/**
|
|
242
|
-
* Creates a queue that processes items
|
|
275
|
+
* Creates a queue that processes items immediately upon addition.
|
|
243
276
|
* Items are processed sequentially in FIFO order by default.
|
|
244
277
|
*
|
|
245
278
|
* This is a simplified wrapper around the Queuer class that only exposes the
|
|
246
|
-
* `addItem` method.
|
|
247
|
-
* For more control over
|
|
248
|
-
* directly which provides methods like `start`, `stop`, `reset`, and more.
|
|
279
|
+
* `addItem` method. The queue is always running and will process items as they are added.
|
|
280
|
+
* For more control over queue processing, use the Queuer class directly.
|
|
249
281
|
*
|
|
250
|
-
*
|
|
282
|
+
* Example usage:
|
|
251
283
|
* ```ts
|
|
252
284
|
* // Basic sequential processing
|
|
253
|
-
* const processItems =
|
|
285
|
+
* const processItems = queue<number>((n) => console.log(n), {
|
|
254
286
|
* wait: 1000,
|
|
255
|
-
* onItemsChange: (queuer) => console.log(queuer.
|
|
256
|
-
* })
|
|
257
|
-
* processItems(1) // Logs: 1
|
|
258
|
-
* processItems(2) // Logs: 2 after 1 completes
|
|
287
|
+
* onItemsChange: (queuer) => console.log(queuer.peekAllItems())
|
|
288
|
+
* });
|
|
289
|
+
* processItems(1); // Logs: 1
|
|
290
|
+
* processItems(2); // Logs: 2 after 1 completes
|
|
259
291
|
*
|
|
260
|
-
* // Priority
|
|
261
|
-
* const processPriority =
|
|
262
|
-
* process: async (n) => console.log(n),
|
|
292
|
+
* // Priority queue
|
|
293
|
+
* const processPriority = queue<number>((n) => console.log(n), {
|
|
263
294
|
* getPriority: n => n // Higher numbers processed first
|
|
264
|
-
* })
|
|
265
|
-
* processPriority(1)
|
|
266
|
-
* processPriority(3) // Processed before 1
|
|
295
|
+
* });
|
|
296
|
+
* processPriority(1);
|
|
297
|
+
* processPriority(3); // Processed before 1
|
|
267
298
|
* ```
|
|
268
299
|
*/
|
|
269
|
-
export declare function queue<TValue>(options: QueuerOptions<TValue>): (item: TValue, position?: QueuePosition, runOnUpdate?: boolean) => boolean;
|
|
300
|
+
export declare function queue<TValue>(fn: (item: TValue) => void, options: QueuerOptions<TValue>): (item: TValue, position?: QueuePosition, runOnUpdate?: boolean) => boolean;
|
|
@@ -24,7 +24,6 @@ class RateLimiter {
|
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
26
|
* Updates the rate limiter options
|
|
27
|
-
* Returns the new options state
|
|
28
27
|
*/
|
|
29
28
|
setOptions(newOptions) {
|
|
30
29
|
this._options = { ...this._options, ...newOptions };
|
|
@@ -72,7 +71,7 @@ class RateLimiter {
|
|
|
72
71
|
this.cleanupOldExecutions();
|
|
73
72
|
if (this._options.windowType === "sliding") {
|
|
74
73
|
if (this._executionTimes.length < this.getLimit()) {
|
|
75
|
-
this.
|
|
74
|
+
this.execute(...args);
|
|
76
75
|
return true;
|
|
77
76
|
}
|
|
78
77
|
} else {
|
|
@@ -80,14 +79,14 @@ class RateLimiter {
|
|
|
80
79
|
const oldestExecution = Math.min(...this._executionTimes);
|
|
81
80
|
const isNewWindow = oldestExecution + this.getWindow() <= now;
|
|
82
81
|
if (isNewWindow || this._executionTimes.length < this.getLimit()) {
|
|
83
|
-
this.
|
|
82
|
+
this.execute(...args);
|
|
84
83
|
return true;
|
|
85
84
|
}
|
|
86
85
|
}
|
|
87
86
|
this.rejectFunction();
|
|
88
87
|
return false;
|
|
89
88
|
}
|
|
90
|
-
|
|
89
|
+
execute(...args) {
|
|
91
90
|
var _a, _b;
|
|
92
91
|
if (!this.getEnabled()) return;
|
|
93
92
|
const now = Date.now();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rate-limiter.cjs","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn>> {\n return this._options as Required<RateLimiterOptions<TFn>>\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)!\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n getLimit(): number {\n return parseFunctionOrValue(this._options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n getWindow(): number {\n return parseFunctionOrValue(this._options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): boolean {\n this.cleanupOldExecutions()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < this.getLimit()) {\n this.executeFunction(...args)\n return true\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + this.getWindow() <= now\n\n if (isNewWindow || this._executionTimes.length < this.getLimit()) {\n this.executeFunction(...args)\n return true\n }\n }\n\n this.rejectFunction()\n return false\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this.getEnabled()) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n this.fn(...args) // execute the function\n this._options.onExecute?.(this)\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.getWindow()\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.getLimit() - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAuCA,MAAM,iBAAoD;AAAA,EACxD,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,QAAQ;AAAA,EACR,YAAY;AACd;AAiCO,MAAM,YAAqC;AAAA,EAMhD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAiC,CAAC;AAOxC,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAAoD;AAC7D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMpD,aAAgD;AAC9C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB;AACpB,WAAOA,MAAqB,qBAAA,KAAK,SAAS,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMzD,WAAmB;AACjB,WAAOA,MAAqB,qBAAA,KAAK,SAAS,OAAO,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,YAAoB;AAClB,WAAOA,MAAqB,qBAAA,KAAK,SAAS,QAAQ,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AK,IAAI,GAAG,KAAK,aAAa,KAAK,gBAAgB,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMlE,uBAA+B;AACzB,QAAA,KAAK,qBAAqB,IAAI,GAAG;AAC5B,aAAA;AAAA,IAAA;AAET,UAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,eAAe;AACxD,WAAO,kBAAkB,KAAK,UAAU,IAAI,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAuCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
1
|
+
{"version":3,"file":"rate-limiter.cjs","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<TFn extends AnyFunction> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean | ((rateLimiter: RateLimiter<TFn>) => boolean)\n /**\n * Maximum number of executions allowed within the time window.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n limit: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn>) => void\n /**\n * Time window in milliseconds within which the limit applies.\n * Can be a number or a callback function that receives the rate limiter instance and returns a number.\n */\n window: number | ((rateLimiter: RateLimiter<TFn>) => number)\n /**\n * Type of window to use for rate limiting\n * - 'fixed': Uses a fixed window that resets after the window period\n * - 'sliding': Uses a sliding window that allows executions as old ones expire\n * Defaults to 'fixed'\n */\n windowType?: 'fixed' | 'sliding'\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\n windowType: 'fixed',\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000, windowType: 'sliding' } // 5 calls per second with sliding window\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<TFn extends AnyFunction> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n */\n setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn>> {\n return this._options as Required<RateLimiterOptions<TFn>>\n }\n\n /**\n * Returns the current enabled state of the rate limiter\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)!\n }\n\n /**\n * Returns the current limit of executions allowed within the time window\n */\n getLimit(): number {\n return parseFunctionOrValue(this._options.limit, this)\n }\n\n /**\n * Returns the current time window in milliseconds\n */\n getWindow(): number {\n return parseFunctionOrValue(this._options.window, this)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): boolean {\n this.cleanupOldExecutions()\n\n if (this._options.windowType === 'sliding') {\n // For sliding window, we can execute if we have capacity in the current window\n if (this._executionTimes.length < this.getLimit()) {\n this.execute(...args)\n return true\n }\n } else {\n // For fixed window, we need to check if we're in a new window\n const now = Date.now()\n const oldestExecution = Math.min(...this._executionTimes)\n const isNewWindow = oldestExecution + this.getWindow() <= now\n\n if (isNewWindow || this._executionTimes.length < this.getLimit()) {\n this.execute(...args)\n return true\n }\n }\n\n this.rejectFunction()\n return false\n }\n\n private execute(...args: Parameters<TFn>): void {\n if (!this.getEnabled()) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n this.fn(...args) // execute the function\n this._options.onExecute?.(this)\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.getWindow()\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.getLimit() - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n if (this.getRemainingInWindow() > 0) {\n return 0\n }\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this.getWindow() - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute with a sliding window\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * windowType: 'sliding',\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: RateLimiterOptions<TFn>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateL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K,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvD,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAuCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
|
|
@@ -74,7 +74,6 @@ export declare class RateLimiter<TFn extends AnyFunction> {
|
|
|
74
74
|
constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn>);
|
|
75
75
|
/**
|
|
76
76
|
* Updates the rate limiter options
|
|
77
|
-
* Returns the new options state
|
|
78
77
|
*/
|
|
79
78
|
setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void;
|
|
80
79
|
/**
|
|
@@ -109,7 +108,7 @@ export declare class RateLimiter<TFn extends AnyFunction> {
|
|
|
109
108
|
* ```
|
|
110
109
|
*/
|
|
111
110
|
maybeExecute(...args: Parameters<TFn>): boolean;
|
|
112
|
-
private
|
|
111
|
+
private execute;
|
|
113
112
|
private rejectFunction;
|
|
114
113
|
private cleanupOldExecutions;
|
|
115
114
|
/**
|
package/dist/cjs/throttler.cjs
CHANGED
|
@@ -21,7 +21,6 @@ class Throttler {
|
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
23
|
* Updates the throttler options
|
|
24
|
-
* Returns the new options state
|
|
25
24
|
*/
|
|
26
25
|
setOptions(newOptions) {
|
|
27
26
|
this._options = { ...this._options, ...newOptions };
|
|
@@ -74,7 +73,7 @@ class Throttler {
|
|
|
74
73
|
const timeSinceLastExecution = now - this._lastExecutionTime;
|
|
75
74
|
const wait = this.getWait();
|
|
76
75
|
if (this._options.leading && timeSinceLastExecution >= wait) {
|
|
77
|
-
this.
|
|
76
|
+
this.execute(...args);
|
|
78
77
|
} else {
|
|
79
78
|
this._lastArgs = args;
|
|
80
79
|
if (!this._timeoutId && this._options.trailing) {
|
|
@@ -82,13 +81,13 @@ class Throttler {
|
|
|
82
81
|
const timeoutDuration = wait - _timeSinceLastExecution;
|
|
83
82
|
this._timeoutId = setTimeout(() => {
|
|
84
83
|
if (this._lastArgs !== void 0) {
|
|
85
|
-
this.
|
|
84
|
+
this.execute(...this._lastArgs);
|
|
86
85
|
}
|
|
87
86
|
}, timeoutDuration);
|
|
88
87
|
}
|
|
89
88
|
}
|
|
90
89
|
}
|
|
91
|
-
|
|
90
|
+
execute(...args) {
|
|
92
91
|
if (!this.getEnabled()) return;
|
|
93
92
|
this.fn(...args);
|
|
94
93
|
this._executionCount++;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\nconst defaultOptions: Required<ThrottlerOptions<any>> = {\n enabled: true,\n leading: true,\n onExecute: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n private _executionCount = 0\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _options: Required<ThrottlerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n
|
|
1
|
+
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyFunction } from './types'\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions<TFn extends AnyFunction> {\n /**\n * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((throttler: Throttler<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to true.\n */\n leading?: boolean\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (throttler: Throttler<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Time window in milliseconds during which the function can only be executed once.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((throttler: Throttler<TFn>) => number)\n}\n\nconst defaultOptions: Required<ThrottlerOptions<any>> = {\n enabled: true,\n leading: true,\n onExecute: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates a throttled function.\n *\n * Throttling ensures a function is called at most once within a specified time window.\n * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent\n * execution timing regardless of call frequency.\n *\n * Supports both leading and trailing edge execution:\n * - Leading: Execute immediately on first call (default: true)\n * - Trailing: Execute after wait period if called during throttle (default: true)\n *\n * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.\n *\n * @example\n * ```ts\n * const throttler = new Throttler(\n * (id: string) => api.getData(id),\n * { wait: 1000 } // Execute at most once per second\n * );\n *\n * // First call executes immediately\n * throttler.maybeExecute('123');\n *\n * // Subsequent calls within 1000ms are throttled\n * throttler.maybeExecute('123'); // Throttled\n * ```\n */\nexport class Throttler<TFn extends AnyFunction> {\n private _executionCount = 0\n private _lastArgs: Parameters<TFn> | undefined\n private _lastExecutionTime = 0\n private _options: Required<ThrottlerOptions<TFn>>\n private _timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the throttler options\n */\n setOptions(newOptions: Partial<ThrottlerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this.cancel()\n }\n }\n\n /**\n * Returns the current throttler options\n */\n getOptions(): Required<ThrottlerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Returns the current enabled state of the throttler\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current wait time in milliseconds\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the throttled function. The execution behavior depends on the throttler options:\n *\n * - If enough time has passed since the last execution (>= wait period):\n * - With leading=true: Executes immediately\n * - With leading=false: Waits for the next trailing execution\n *\n * - If within the wait period:\n * - With trailing=true: Schedules execution for end of wait period\n * - With trailing=false: Drops the execution\n *\n * @example\n * ```ts\n * const throttled = new Throttler(fn, { wait: 1000 });\n *\n * // First call executes immediately\n * throttled.maybeExecute('a', 'b');\n *\n * // Call during wait period - gets throttled\n * throttled.maybeExecute('c', 'd');\n * ```\n */\n maybeExecute(...args: Parameters<TFn>): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n const wait = this.getWait()\n\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= wait) {\n this.execute(...args)\n } else {\n // Store the most recent arguments for potential trailing execution\n this._lastArgs = args\n\n // Set up trailing execution if not already scheduled\n if (!this._timeoutId && this._options.trailing) {\n const _timeSinceLastExecution = this._lastExecutionTime\n ? now - this._lastExecutionTime\n : 0\n const timeoutDuration = wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(() => {\n if (this._lastArgs !== undefined) {\n this.execute(...this._lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n private execute(...args: Parameters<TFn>): void {\n if (!this.getEnabled()) return\n this.fn(...args) // EXECUTE!\n this._executionCount++\n this._lastExecutionTime = Date.now()\n this._timeoutId = undefined\n this._lastArgs = undefined\n this._options.onExecute(this)\n }\n\n /**\n * Cancels any pending trailing execution and clears internal state.\n *\n * If a trailing execution is scheduled (due to throttling with trailing=true),\n * this will prevent that execution from occurring. The internal timeout and\n * stored arguments will be cleared.\n *\n * Has no effect if there is no pending execution.\n */\n cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = undefined\n this._lastArgs = undefined\n }\n }\n\n /**\n * Returns the last execution time\n */\n getLastExecutionTime(): number {\n return this._lastExecutionTime\n }\n\n /**\n * Returns the next execution time\n */\n getNextExecutionTime(): number {\n return this._lastExecutionTime + this.getWait()\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns `true` if there is a pending execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && !!this._timeoutId\n }\n}\n\n/**\n * Creates a throttled function that limits how often the provided function can execute.\n *\n * Throttling ensures a function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting\n * expensive operations or UI updates.\n *\n * The throttled function can be configured to execute on the leading and/or trailing\n * edge of the throttle window via options.\n *\n * For handling bursts of events, consider using debounce() instead. For hard execution\n * limits, consider using rateLimit().\n *\n * @example\n * ```ts\n * // Basic throttling - max once per second\n * const throttled = throttle(updateUI, { wait: 1000 });\n *\n * // Configure leading/trailing execution\n * const throttled = throttle(saveData, {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: true // Execute again after delay if called during wait\n * });\n * ```\n */\nexport function throttle<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: ThrottlerOptions<TFn>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAmCA,MAAM,iBAAkD;AAAA,EACtD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU;AAAA,EACV,MAAM;AACR;AA6BO,MAAM,UAAmC;AAAA,EAO9C,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,kBAAkB;AAE1B,SAAQ,qBAAqB;AAQ3B,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,WAAW,YAAkD;AAC3D,SAAK,WAAW,EAAE,GAAG,KAAK,UAAU,GAAG,WAAW;AAG9C,QAAA,CAAC,KAAK,SAAS,SAAS;AAC1B,WAAK,OAAO;AAAA,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAMF,aAA8C;AAC5C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,aAAsB;AACpB,WAAOA,MAAqB,qBAAA,KAAK,SAAS,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMzD,UAAkB;AAChB,WAAOA,MAAqB,qBAAA,KA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Q;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMhD,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK,WAAA,KAAgB,CAAC,CAAC,KAAK;AAAA,EAAA;AAEvC;AA4BgB,SAAA,SACd,IACA,gBACA;AACA,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
|
package/dist/cjs/throttler.d.cts
CHANGED
|
@@ -67,7 +67,6 @@ export declare class Throttler<TFn extends AnyFunction> {
|
|
|
67
67
|
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
|
|
68
68
|
/**
|
|
69
69
|
* Updates the throttler options
|
|
70
|
-
* Returns the new options state
|
|
71
70
|
*/
|
|
72
71
|
setOptions(newOptions: Partial<ThrottlerOptions<TFn>>): void;
|
|
73
72
|
/**
|
|
@@ -105,7 +104,7 @@ export declare class Throttler<TFn extends AnyFunction> {
|
|
|
105
104
|
* ```
|
|
106
105
|
*/
|
|
107
106
|
maybeExecute(...args: Parameters<TFn>): void;
|
|
108
|
-
private
|
|
107
|
+
private execute;
|
|
109
108
|
/**
|
|
110
109
|
* Cancels any pending trailing execution and clears internal state.
|
|
111
110
|
*
|
|
@@ -96,10 +96,10 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
96
96
|
private _settleCount;
|
|
97
97
|
private _successCount;
|
|
98
98
|
private _timeoutId;
|
|
99
|
+
private _resolvePreviousPromise;
|
|
99
100
|
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
|
|
100
101
|
/**
|
|
101
102
|
* Updates the debouncer options
|
|
102
|
-
* Returns the new options state
|
|
103
103
|
*/
|
|
104
104
|
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void;
|
|
105
105
|
/**
|
|
@@ -129,7 +129,7 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
129
129
|
* @throws The error from the debounced function if no onError handler is configured
|
|
130
130
|
*/
|
|
131
131
|
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
132
|
-
private
|
|
132
|
+
private execute;
|
|
133
133
|
/**
|
|
134
134
|
* Cancel without resetting _canLeadingExecute
|
|
135
135
|
*/
|
|
@@ -16,6 +16,7 @@ class AsyncDebouncer {
|
|
|
16
16
|
this._settleCount = 0;
|
|
17
17
|
this._successCount = 0;
|
|
18
18
|
this._timeoutId = null;
|
|
19
|
+
this._resolvePreviousPromise = null;
|
|
19
20
|
this._options = {
|
|
20
21
|
...defaultOptions,
|
|
21
22
|
...initialOptions,
|
|
@@ -24,7 +25,6 @@ class AsyncDebouncer {
|
|
|
24
25
|
}
|
|
25
26
|
/**
|
|
26
27
|
* Updates the debouncer options
|
|
27
|
-
* Returns the new options state
|
|
28
28
|
*/
|
|
29
29
|
setOptions(newOptions) {
|
|
30
30
|
this._options = { ...this._options, ...newOptions };
|
|
@@ -69,23 +69,25 @@ class AsyncDebouncer {
|
|
|
69
69
|
this._lastArgs = args;
|
|
70
70
|
if (this._options.leading && this._canLeadingExecute) {
|
|
71
71
|
this._canLeadingExecute = false;
|
|
72
|
-
await this.
|
|
72
|
+
await this.execute(...args);
|
|
73
73
|
return this._lastResult;
|
|
74
74
|
}
|
|
75
75
|
if (this._options.trailing) {
|
|
76
76
|
this._isPending = true;
|
|
77
77
|
}
|
|
78
78
|
return new Promise((resolve) => {
|
|
79
|
+
this._resolvePreviousPromise = resolve;
|
|
79
80
|
this._timeoutId = setTimeout(async () => {
|
|
80
81
|
if (this._options.trailing && this._lastArgs) {
|
|
81
|
-
await this.
|
|
82
|
+
await this.execute(...this._lastArgs);
|
|
82
83
|
}
|
|
83
84
|
this._canLeadingExecute = true;
|
|
85
|
+
this._resolvePreviousPromise = null;
|
|
84
86
|
resolve(this._lastResult);
|
|
85
87
|
}, this.getWait());
|
|
86
88
|
});
|
|
87
89
|
}
|
|
88
|
-
async
|
|
90
|
+
async execute(...args) {
|
|
89
91
|
var _a, _b, _c, _d, _e, _f;
|
|
90
92
|
if (!this.getEnabled()) return void 0;
|
|
91
93
|
this._abortController = new AbortController();
|
|
@@ -99,8 +101,6 @@ class AsyncDebouncer {
|
|
|
99
101
|
(_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
|
|
100
102
|
if (this._options.throwOnError) {
|
|
101
103
|
throw error;
|
|
102
|
-
} else {
|
|
103
|
-
console.error(error);
|
|
104
104
|
}
|
|
105
105
|
} finally {
|
|
106
106
|
this._isExecuting = false;
|
|
@@ -123,6 +123,10 @@ class AsyncDebouncer {
|
|
|
123
123
|
this._abortController.abort();
|
|
124
124
|
this._abortController = null;
|
|
125
125
|
}
|
|
126
|
+
if (this._resolvePreviousPromise) {
|
|
127
|
+
this._resolvePreviousPromise(this._lastResult);
|
|
128
|
+
this._resolvePreviousPromise = null;
|
|
129
|
+
}
|
|
126
130
|
this._lastArgs = void 0;
|
|
127
131
|
this._isPending = false;
|
|
128
132
|
this._isExecuting = false;
|