@tanstack/pacer 0.1.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 (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
package/src/queuer.ts ADDED
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Options for configuring a Queuer instance
3
+ */
4
+ export interface QueuerOptions<TValue> {
5
+ /**
6
+ * Default position to add items to the queuer
7
+ * @default 'back'
8
+ */
9
+ addItemsTo?: QueuePosition
10
+ /**
11
+ * Default position to get items from during processing
12
+ * @default 'front'
13
+ */
14
+ getItemsFrom?: QueuePosition
15
+ /**
16
+ * Function to determine priority of items in the queuer
17
+ * Higher priority items will be processed first
18
+ */
19
+ getPriority?: (item: TValue) => number
20
+ /**
21
+ * Initial items to populate the queuer with
22
+ */
23
+ initialItems?: Array<TValue>
24
+ /**
25
+ * Maximum number of items allowed in the queuer
26
+ */
27
+ maxSize?: number
28
+ /**
29
+ * Callback fired whenever an item is removed from the queuer
30
+ */
31
+ onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void
32
+ /**
33
+ * Callback fired whenever an item is added or removed from the queuer
34
+ */
35
+ onUpdate?: (queuer: Queuer<TValue>) => void
36
+ /**
37
+ * Whether the queuer should start processing tasks immediately
38
+ */
39
+ started?: boolean
40
+ /**
41
+ * Time in milliseconds to wait between processing items
42
+ */
43
+ wait?: number
44
+ }
45
+
46
+ const defaultOptions: Required<QueuerOptions<any>> = {
47
+ addItemsTo: 'back',
48
+ getItemsFrom: 'front',
49
+ getPriority: () => 0,
50
+ initialItems: [],
51
+ maxSize: Infinity,
52
+ onGetNextItem: () => {},
53
+ onUpdate: () => {},
54
+ started: false,
55
+ wait: 0,
56
+ }
57
+
58
+ /**
59
+ * Position type for addItem and getNextItem operations
60
+ */
61
+ export type QueuePosition = 'front' | 'back'
62
+
63
+ /**
64
+ * A flexible queue data structure that defaults to FIFO (First In First Out) behavior
65
+ * with optional position overrides for stack-like or double-ended operations.
66
+ *
67
+ * The queuer can automatically process items as they are added, with configurable
68
+ * wait times between processing each item. Processing can be started/stopped
69
+ * and the queuer will maintain its state.
70
+ *
71
+ * Supports priority-based ordering when a getPriority function is provided.
72
+ * Items with higher priority values will be processed first.
73
+ *
74
+ * Default queue behavior:
75
+ * - addItem(item): adds to back of queuer
76
+ * - getNextItem(): removes and returns from front of queuer
77
+ *
78
+ * Stack (LIFO) behavior:
79
+ * - addItem(item, 'back'): adds to back
80
+ * - getNextItem('back'): removes and returns from back
81
+ *
82
+ * Double-ended queuer behavior:
83
+ * - addItem(item, position): adds to specified position ('front' or 'back')
84
+ * - getNextItem(position): removes and returns from specified position
85
+ *
86
+ * Processing behavior:
87
+ * - start(): begins processing items in the queuer
88
+ * - stop(): pauses processing
89
+ * - wait: configurable delay between processing items
90
+ * - onUpdate/onGetNextItem: callbacks for monitoring queuer state
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * // FIFO queuer
95
+ * const queuer = new Queuer<number>();
96
+ * queuer.addItem(1); // [1]
97
+ * queuer.addItem(2); // [1, 2]
98
+ * queuer.getNextItem(); // returns 1, queuer is [2]
99
+ *
100
+ * // Priority queuer with processing
101
+ * const priorityQueue = new Queuer<number>({
102
+ * getPriority: (n) => n, // Higher numbers have priority
103
+ * started: true, // Begin processing immediately
104
+ * wait: 1000, // Wait 1s between items
105
+ * onGetNextItem: (item) => console.log(item)
106
+ * });
107
+ * priorityQueue.addItem(1); // [1]
108
+ * priorityQueue.addItem(3); // [3, 1] - 3 processed first
109
+ * priorityQueue.addItem(2); // [3, 2, 1]
110
+ * ```
111
+ */
112
+ export class Queuer<TValue> {
113
+ protected options: Required<QueuerOptions<TValue>>
114
+ private items: Array<TValue> = []
115
+ private executionCount = 0
116
+ private onUpdates: Array<(item: TValue) => void> = []
117
+ private running: boolean
118
+ private pendingTick = false
119
+
120
+ constructor(initialOptions: QueuerOptions<TValue> = defaultOptions) {
121
+ this.options = { ...defaultOptions, ...initialOptions }
122
+ this.running = this.options.started
123
+
124
+ for (let i = 0; i < this.options.initialItems.length; i++) {
125
+ const item = this.options.initialItems[i]!
126
+ const isLast = i === this.options.initialItems.length - 1
127
+ this.addItem(item, this.options.addItemsTo, isLast)
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Processes items in the queuer
133
+ */
134
+ protected tick() {
135
+ if (!this.running) {
136
+ this.pendingTick = false
137
+ return
138
+ }
139
+ while (!this.isEmpty()) {
140
+ const nextItem = this.getNextItem(this.options.getItemsFrom)
141
+ if (nextItem === undefined) {
142
+ break
143
+ }
144
+ this.onUpdates.forEach((cb) => cb(nextItem))
145
+
146
+ if (this.options.wait > 0) {
147
+ // Use setTimeout to wait before processing next item
148
+ setTimeout(() => this.tick(), this.options.wait)
149
+ return
150
+ }
151
+
152
+ this.tick()
153
+ }
154
+ this.pendingTick = false
155
+ }
156
+
157
+ /**
158
+ * Updates the queuer options
159
+ * Returns the new options state
160
+ */
161
+ setOptions(
162
+ newOptions: Partial<QueuerOptions<TValue>>,
163
+ ): QueuerOptions<TValue> {
164
+ this.options = { ...this.options, ...newOptions }
165
+ return this.options
166
+ }
167
+
168
+ /**
169
+ * Adds an item to the queuer and starts processing if not already running
170
+ * @returns true if item was added, false if queuer is full
171
+ */
172
+ addItem(
173
+ item: TValue,
174
+ position: QueuePosition = this.options.addItemsTo,
175
+ runOnUpdate: boolean = true,
176
+ ): boolean {
177
+ if (this.isFull()) {
178
+ return false
179
+ }
180
+
181
+ if (this.options.getPriority !== defaultOptions.getPriority) {
182
+ // If custom priority function is provided, insert based on priority
183
+ const priority = this.options.getPriority(item)
184
+ const insertIndex = this.items.findIndex(
185
+ (existing) => this.options.getPriority(existing) > priority,
186
+ )
187
+
188
+ if (insertIndex === -1) {
189
+ this.items.push(item)
190
+ } else {
191
+ this.items.splice(insertIndex, 0, item)
192
+ }
193
+ } else {
194
+ // Default FIFO/LIFO behavior
195
+ if (position === 'front') {
196
+ this.items.unshift(item)
197
+ } else {
198
+ this.items.push(item)
199
+ }
200
+ }
201
+
202
+ if (this.running && !this.pendingTick) {
203
+ this.pendingTick = true
204
+ this.tick()
205
+ }
206
+ if (runOnUpdate) {
207
+ this.options.onUpdate(this)
208
+ }
209
+ return true
210
+ }
211
+
212
+ /**
213
+ * Removes and returns an item from the queuer using shift (default) or pop
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * // Standard FIFO queuer
218
+ * queuer.getNextItem()
219
+ * // Stack-like behavior (LIFO)
220
+ * queuer.getNextItem('back')
221
+ * ```
222
+ */
223
+ getNextItem(
224
+ position: QueuePosition = this.options.getItemsFrom,
225
+ ): TValue | undefined {
226
+ let item: TValue | undefined
227
+
228
+ if (position === 'front') {
229
+ item = this.items.shift()
230
+ } else {
231
+ item = this.items.pop()
232
+ }
233
+
234
+ if (item !== undefined) {
235
+ this.executionCount++
236
+ this.options.onUpdate(this)
237
+ this.options.onGetNextItem(item, this)
238
+ }
239
+ return item
240
+ }
241
+
242
+ /**
243
+ * Returns an item without removing it
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * // Look at next item to getNextItem
248
+ * queuer.peek()
249
+ * // Look at last item (like stack top)
250
+ * queuer.peek('back')
251
+ * ```
252
+ */
253
+ peek(
254
+ position: QueuePosition = this.options.getItemsFrom,
255
+ ): TValue | undefined {
256
+ if (position === 'front') {
257
+ return this.items[0]
258
+ }
259
+ return this.items[this.items.length - 1]
260
+ }
261
+
262
+ /**
263
+ * Returns true if the queuer is empty
264
+ */
265
+ isEmpty(): boolean {
266
+ return this.items.length === 0
267
+ }
268
+
269
+ /**
270
+ * Returns true if the queuer is full
271
+ */
272
+ isFull(): boolean {
273
+ return this.items.length >= this.options.maxSize
274
+ }
275
+
276
+ /**
277
+ * Returns the current size of the queuer
278
+ */
279
+ size(): number {
280
+ return this.items.length
281
+ }
282
+
283
+ /**
284
+ * Removes all items from the queuer
285
+ */
286
+ clear(): void {
287
+ this.items = []
288
+ this.options.onUpdate(this)
289
+ }
290
+
291
+ /**
292
+ * Resets the queuer to its initial state
293
+ */
294
+ reset(withInitialItems?: boolean): void {
295
+ this.clear()
296
+ this.executionCount = 0
297
+ if (withInitialItems) {
298
+ this.items = [...this.options.initialItems]
299
+ }
300
+ this.running = this.options.started
301
+ }
302
+
303
+ /**
304
+ * Returns a copy of all items in the queuer
305
+ */
306
+ getAllItems(): Array<TValue> {
307
+ return [...this.items]
308
+ }
309
+
310
+ /**
311
+ * Returns the number of items that have been removed from the queuer
312
+ */
313
+ getExecutionCount(): number {
314
+ return this.executionCount
315
+ }
316
+
317
+ /**
318
+ * Adds a callback to be called when an item is processed
319
+ */
320
+ onUpdate(cb: (item: TValue) => void) {
321
+ this.onUpdates.push(cb)
322
+ return () => {
323
+ this.onUpdates = this.onUpdates.filter((d) => d !== cb)
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Stops the queuer from processing items
329
+ */
330
+ stop() {
331
+ this.running = false
332
+ this.pendingTick = false
333
+ this.options.onUpdate(this)
334
+ }
335
+
336
+ /**
337
+ * Starts the queuer and processes items
338
+ */
339
+ start() {
340
+ this.running = true
341
+ if (!this.pendingTick && !this.isEmpty()) {
342
+ this.pendingTick = true
343
+ this.tick()
344
+ }
345
+ this.options.onUpdate(this)
346
+ }
347
+
348
+ /**
349
+ * Returns true if the queuer is running
350
+ */
351
+ isRunning() {
352
+ return this.running
353
+ }
354
+
355
+ /**
356
+ * Returns true if the queuer is running but has no items to process
357
+ */
358
+ isIdle() {
359
+ return this.running && this.isEmpty()
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Creates a queue that processes items in a queuer immediately upon addition.
365
+ * Items are processed sequentially in FIFO order by default.
366
+ *
367
+ * This is a simplified wrapper around the Queuer class that only exposes the
368
+ * `addItem` method. This queue is always running and will process items as they are added.
369
+ * For more control over queuer processing, use the Queuer class
370
+ * directly which provides methods like `start`, `stop`, `reset`, and more.
371
+ *
372
+ * @example
373
+ * ```ts
374
+ * // Basic sequential processing
375
+ * const processItems = queuer<number>({
376
+ * wait: 1000,
377
+ * onUpdate: (queuer) => console.log(queuer.getAllItems())
378
+ * })
379
+ * processItems(1) // Logs: 1
380
+ * processItems(2) // Logs: 2 after 1 completes
381
+ *
382
+ * // Priority queuer
383
+ * const processPriority = queuer<number>({
384
+ * process: async (n) => console.log(n),
385
+ * getPriority: n => n // Higher numbers processed first
386
+ * })
387
+ * processPriority(1)
388
+ * processPriority(3) // Processed before 1
389
+ * ```
390
+ */
391
+ export function queue<TValue>(options: QueuerOptions<TValue> = {}) {
392
+ const queuer = new Queuer<TValue>({ ...options, started: true })
393
+ return queuer.addItem.bind(queuer)
394
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Information about a rate limit rejection
3
+ */
4
+ export interface RateLimitRejectionInfo {
5
+ /**
6
+ * Number of milliseconds until the next execution will be possible
7
+ */
8
+ msUntilNextWindow: number
9
+ /**
10
+ * Current number of executions in the window
11
+ */
12
+ currentExecutions: number
13
+ /**
14
+ * Maximum allowed executions per window
15
+ */
16
+ limit: number
17
+ /**
18
+ * Total number of rejections that have occurred
19
+ */
20
+ rejectionCount: number
21
+ }
22
+
23
+ /**
24
+ * Options for configuring a rate-limited function
25
+ */
26
+ export interface RateLimiterOptions {
27
+ /**
28
+ * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
29
+ * Defaults to true.
30
+ */
31
+ enabled?: boolean
32
+ /**
33
+ * Maximum number of executions allowed within the time window
34
+ */
35
+ limit: number
36
+ /**
37
+ * Time window in milliseconds within which the limit applies
38
+ */
39
+ window: number
40
+ /**
41
+ * Optional callback function that is called when an execution is rejected due to rate limiting
42
+ */
43
+ onReject?: (info: RateLimitRejectionInfo) => void
44
+ }
45
+
46
+ const defaultOptions: Required<Omit<RateLimiterOptions, 'onReject'>> = {
47
+ enabled: true,
48
+ limit: 1,
49
+ window: 0,
50
+ }
51
+
52
+ /**
53
+ * A class that creates a rate-limited function.
54
+ *
55
+ * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
56
+ * then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
57
+ * all executions happen immediately, followed by a complete block.
58
+ *
59
+ * For smoother execution patterns, consider using:
60
+ * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
61
+ * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
62
+ *
63
+ * Rate limiting is best used for hard API limits or resource constraints. For UI updates or
64
+ * smoothing out frequent events, throttling or debouncing usually provide better user experience.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const rateLimiter = new RateLimiter(
69
+ * (id: string) => api.getData(id),
70
+ * { limit: 5, window: 1000 } // 5 calls per second
71
+ * );
72
+ *
73
+ * // Will execute immediately until limit reached, then block
74
+ * rateLimiter.maybeExecute('123');
75
+ * ```
76
+ */
77
+ export class RateLimiter<
78
+ TFn extends (...args: Array<any>) => any,
79
+ TArgs extends Parameters<TFn>,
80
+ > {
81
+ private executionCount = 0
82
+ private rejectionCount = 0
83
+ private executionTimes: Array<number> = []
84
+ private options: RateLimiterOptions
85
+
86
+ constructor(
87
+ private fn: TFn,
88
+ initialOptions: RateLimiterOptions,
89
+ ) {
90
+ this.options = {
91
+ ...defaultOptions,
92
+ ...initialOptions,
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Updates the rate limiter options
98
+ * Returns the new options state
99
+ */
100
+ setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions {
101
+ this.options = {
102
+ ...this.options,
103
+ ...newOptions,
104
+ }
105
+ return this.options
106
+ }
107
+
108
+ /**
109
+ * Returns the number of times the function has been executed
110
+ */
111
+ getExecutionCount(): number {
112
+ return this.executionCount
113
+ }
114
+
115
+ /**
116
+ * Returns the number of times the function has been rejected
117
+ */
118
+ getRejectionCount(): number {
119
+ return this.rejectionCount
120
+ }
121
+
122
+ /**
123
+ * Returns the number of remaining executions allowed in the current window
124
+ */
125
+ getRemainingInWindow(): number {
126
+ this.cleanupOldExecutions()
127
+ return Math.max(0, this.options.limit - this.executionTimes.length)
128
+ }
129
+
130
+ /**
131
+ * Attempts to execute the rate-limited function if within the configured limits.
132
+ * Will reject execution if the number of calls in the current window exceeds the limit.
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });
137
+ *
138
+ * // First 5 calls will return true
139
+ * rateLimiter.maybeExecute('arg1', 'arg2'); // true
140
+ *
141
+ * // Additional calls within the window will return false
142
+ * rateLimiter.maybeExecute('arg1', 'arg2'); // false
143
+ * ```
144
+ */
145
+ maybeExecute(...args: TArgs): boolean {
146
+ this.cleanupOldExecutions()
147
+
148
+ if (this.executionTimes.length < this.options.limit) {
149
+ this.executeFunction(...args)
150
+ return true
151
+ }
152
+
153
+ this.rejectFunction()
154
+
155
+ return false
156
+ }
157
+
158
+ private executeFunction(...args: TArgs): void {
159
+ if (!this.options.enabled) return
160
+ const now = Date.now()
161
+ this.executionCount++
162
+ this.executionTimes.push(now)
163
+ this.fn(...args)
164
+ }
165
+
166
+ private rejectFunction(): void {
167
+ this.rejectionCount++
168
+ if (this.options.onReject) {
169
+ const oldestExecution = Math.min(...this.executionTimes)
170
+ const msUntilNextWindow =
171
+ oldestExecution + this.options.window - Date.now()
172
+
173
+ this.options.onReject({
174
+ msUntilNextWindow,
175
+ currentExecutions: this.executionTimes.length,
176
+ limit: this.options.limit,
177
+ rejectionCount: this.rejectionCount,
178
+ })
179
+ }
180
+ }
181
+
182
+ private cleanupOldExecutions(): void {
183
+ const now = Date.now()
184
+ const windowStart = now - this.options.window
185
+ this.executionTimes = this.executionTimes.filter(
186
+ (time) => time > windowStart,
187
+ )
188
+ }
189
+
190
+ /**
191
+ * Resets the rate limiter state
192
+ */
193
+ reset(): void {
194
+ this.executionTimes = []
195
+ this.executionCount = 0
196
+ this.rejectionCount = 0
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.
202
+ *
203
+ * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
204
+ * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
205
+ * - A throttler ensures even spacing between executions, which can be better for consistent performance
206
+ * - A debouncer collapses multiple calls into one, which is better for handling bursts of events
207
+ *
208
+ * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
209
+ * need to enforce a hard limit on the number of executions within a time period.
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * // Rate limit to 5 calls per minute
214
+ * const rateLimited = rateLimit(makeApiCall, {
215
+ * limit: 5,
216
+ * window: 60000,
217
+ * onReject: ({ msUntilNextWindow }) => {
218
+ * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
219
+ * }
220
+ * });
221
+ *
222
+ * // First 5 calls will execute immediately
223
+ * // Additional calls will be rejected until the minute window resets
224
+ * rateLimited();
225
+ *
226
+ * // For more even execution, consider using throttle instead:
227
+ * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
228
+ * ```
229
+ */
230
+ export function rateLimit<TFn extends (...args: Array<any>) => any>(
231
+ fn: TFn,
232
+ initialOptions: Omit<RateLimiterOptions, 'enabled'>,
233
+ ) {
234
+ const rateLimiter = new RateLimiter(fn, initialOptions)
235
+ return rateLimiter.maybeExecute.bind(rateLimiter)
236
+ }