@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.
- package/LICENSE +21 -0
- package/dist/cjs/async-debouncer.cjs +109 -0
- package/dist/cjs/async-debouncer.cjs.map +1 -0
- package/dist/cjs/async-debouncer.d.cts +99 -0
- package/dist/cjs/async-queuer.cjs +293 -0
- package/dist/cjs/async-queuer.cjs.map +1 -0
- package/dist/cjs/async-queuer.d.cts +197 -0
- package/dist/cjs/async-rate-limiter.cjs +122 -0
- package/dist/cjs/async-rate-limiter.cjs.map +1 -0
- package/dist/cjs/async-rate-limiter.d.cts +132 -0
- package/dist/cjs/async-throttler.cjs +115 -0
- package/dist/cjs/async-throttler.cjs.map +1 -0
- package/dist/cjs/async-throttler.d.cts +93 -0
- package/dist/cjs/compare.cjs +72 -0
- package/dist/cjs/compare.cjs.map +1 -0
- package/dist/cjs/compare.d.cts +12 -0
- package/dist/cjs/debouncer.cjs +74 -0
- package/dist/cjs/debouncer.cjs.map +1 -0
- package/dist/cjs/debouncer.d.cts +96 -0
- package/dist/cjs/index.cjs +32 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/index.d.cts +9 -0
- package/dist/cjs/queuer.cjs +231 -0
- package/dist/cjs/queuer.cjs.map +1 -0
- package/dist/cjs/queuer.d.cts +221 -0
- package/dist/cjs/rate-limiter.cjs +115 -0
- package/dist/cjs/rate-limiter.cjs.map +1 -0
- package/dist/cjs/rate-limiter.d.cts +147 -0
- package/dist/cjs/throttler.cjs +120 -0
- package/dist/cjs/throttler.cjs.map +1 -0
- package/dist/cjs/throttler.d.cts +139 -0
- package/dist/esm/async-debouncer.d.ts +99 -0
- package/dist/esm/async-debouncer.js +109 -0
- package/dist/esm/async-debouncer.js.map +1 -0
- package/dist/esm/async-queuer.d.ts +197 -0
- package/dist/esm/async-queuer.js +293 -0
- package/dist/esm/async-queuer.js.map +1 -0
- package/dist/esm/async-rate-limiter.d.ts +132 -0
- package/dist/esm/async-rate-limiter.js +122 -0
- package/dist/esm/async-rate-limiter.js.map +1 -0
- package/dist/esm/async-throttler.d.ts +93 -0
- package/dist/esm/async-throttler.js +115 -0
- package/dist/esm/async-throttler.js.map +1 -0
- package/dist/esm/compare.d.ts +12 -0
- package/dist/esm/compare.js +72 -0
- package/dist/esm/compare.js.map +1 -0
- package/dist/esm/debouncer.d.ts +96 -0
- package/dist/esm/debouncer.js +74 -0
- package/dist/esm/debouncer.js.map +1 -0
- package/dist/esm/index.d.ts +9 -0
- package/dist/esm/index.js +32 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/queuer.d.ts +221 -0
- package/dist/esm/queuer.js +231 -0
- package/dist/esm/queuer.js.map +1 -0
- package/dist/esm/rate-limiter.d.ts +147 -0
- package/dist/esm/rate-limiter.js +115 -0
- package/dist/esm/rate-limiter.js.map +1 -0
- package/dist/esm/throttler.d.ts +139 -0
- package/dist/esm/throttler.js +120 -0
- package/dist/esm/throttler.js.map +1 -0
- package/package.json +150 -0
- package/src/async-debouncer.ts +197 -0
- package/src/async-queuer.ts +447 -0
- package/src/async-rate-limiter.ts +228 -0
- package/src/async-throttler.ts +194 -0
- package/src/compare.ts +105 -0
- package/src/debouncer.ts +164 -0
- package/src/index.ts +9 -0
- package/src/queuer.ts +394 -0
- package/src/rate-limiter.ts +236 -0
- package/src/throttler.ts +222 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import type { RateLimitRejectionInfo } from './rate-limiter'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Options for configuring an async rate-limited function
|
|
5
|
+
*/
|
|
6
|
+
export interface AsyncRateLimiterOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
9
|
+
* Defaults to true.
|
|
10
|
+
*/
|
|
11
|
+
enabled?: boolean
|
|
12
|
+
/**
|
|
13
|
+
* Maximum number of executions allowed within the time window
|
|
14
|
+
*/
|
|
15
|
+
limit: number
|
|
16
|
+
/**
|
|
17
|
+
* Time window in milliseconds within which the limit applies
|
|
18
|
+
*/
|
|
19
|
+
window: number
|
|
20
|
+
/**
|
|
21
|
+
* Optional callback function that is called when an execution is rejected due to rate limiting
|
|
22
|
+
*/
|
|
23
|
+
onReject?: (info: RateLimitRejectionInfo) => void
|
|
24
|
+
/**
|
|
25
|
+
* Optional error handler for when the rate-limited function throws
|
|
26
|
+
*/
|
|
27
|
+
onError?: (error: unknown) => void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A class that creates an async rate-limited function.
|
|
32
|
+
*
|
|
33
|
+
* Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,
|
|
34
|
+
* then blocks all subsequent calls until the window passes. This can lead to "bursty" behavior where
|
|
35
|
+
* all executions happen immediately, followed by a complete block.
|
|
36
|
+
*
|
|
37
|
+
* For smoother execution patterns, consider using:
|
|
38
|
+
* - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)
|
|
39
|
+
* - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)
|
|
40
|
+
*
|
|
41
|
+
* Rate limiting is best used for hard API limits or resource constraints. For UI updates or
|
|
42
|
+
* smoothing out frequent events, throttling or debouncing usually provide better user experience.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* const rateLimiter = new AsyncRateLimiter(
|
|
47
|
+
* async (id: string) => await api.getData(id),
|
|
48
|
+
* { limit: 5, window: 1000 } // 5 calls per second
|
|
49
|
+
* );
|
|
50
|
+
*
|
|
51
|
+
* // Will execute immediately until limit reached, then block
|
|
52
|
+
* await rateLimiter.maybeExecute('123');
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export class AsyncRateLimiter<
|
|
56
|
+
TFn extends (...args: Array<any>) => Promise<any>,
|
|
57
|
+
TArgs extends Parameters<TFn>,
|
|
58
|
+
> {
|
|
59
|
+
private executionCount = 0
|
|
60
|
+
private rejectionCount = 0
|
|
61
|
+
private executionTimes: Array<number> = []
|
|
62
|
+
private options: AsyncRateLimiterOptions
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
private fn: TFn,
|
|
66
|
+
initialOptions: AsyncRateLimiterOptions,
|
|
67
|
+
) {
|
|
68
|
+
this.options = {
|
|
69
|
+
enabled: true,
|
|
70
|
+
...initialOptions,
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Updates the rate limiter options
|
|
76
|
+
* Returns the new options state
|
|
77
|
+
*/
|
|
78
|
+
setOptions(
|
|
79
|
+
newOptions: Partial<AsyncRateLimiterOptions>,
|
|
80
|
+
): AsyncRateLimiterOptions {
|
|
81
|
+
this.options = {
|
|
82
|
+
...this.options,
|
|
83
|
+
...newOptions,
|
|
84
|
+
}
|
|
85
|
+
return this.options
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Returns the number of times the function has been executed
|
|
90
|
+
*/
|
|
91
|
+
getExecutionCount(): number {
|
|
92
|
+
return this.executionCount
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Returns the number of times the function has been rejected
|
|
97
|
+
*/
|
|
98
|
+
getRejectionCount(): number {
|
|
99
|
+
return this.rejectionCount
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Returns the number of remaining executions allowed in the current window
|
|
104
|
+
*/
|
|
105
|
+
getRemainingInWindow(): number {
|
|
106
|
+
this.cleanupOldExecutions()
|
|
107
|
+
return Math.max(0, this.options.limit - this.executionTimes.length)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Attempts to execute the rate-limited function if within the configured limits.
|
|
112
|
+
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
113
|
+
* If execution is allowed, waits for any previous execution to complete before proceeding.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
|
|
118
|
+
*
|
|
119
|
+
* // First 5 calls will execute
|
|
120
|
+
* await rateLimiter.maybeExecute('arg1', 'arg2');
|
|
121
|
+
*
|
|
122
|
+
* // Additional calls within the window will be rejected
|
|
123
|
+
* await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
async maybeExecute(...args: TArgs): Promise<boolean> {
|
|
127
|
+
this.cleanupOldExecutions()
|
|
128
|
+
|
|
129
|
+
if (this.executionTimes.length < this.options.limit) {
|
|
130
|
+
await this.executeFunction(...args)
|
|
131
|
+
return true
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
this.rejectFunction()
|
|
135
|
+
return false
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private async executeFunction(...args: TArgs): Promise<void> {
|
|
139
|
+
if (!this.options.enabled) return
|
|
140
|
+
const now = Date.now()
|
|
141
|
+
this.executionCount++
|
|
142
|
+
this.executionTimes.push(now)
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
await this.fn(...args)
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (this.options.onError) {
|
|
148
|
+
try {
|
|
149
|
+
this.options.onError(error)
|
|
150
|
+
} catch {
|
|
151
|
+
// Ignore errors from error handler
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
throw error
|
|
155
|
+
} finally {
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private rejectFunction(): void {
|
|
160
|
+
this.rejectionCount++
|
|
161
|
+
if (this.options.onReject) {
|
|
162
|
+
const oldestExecution = Math.min(...this.executionTimes)
|
|
163
|
+
const msUntilNextWindow =
|
|
164
|
+
oldestExecution + this.options.window - Date.now()
|
|
165
|
+
|
|
166
|
+
this.options.onReject({
|
|
167
|
+
msUntilNextWindow,
|
|
168
|
+
currentExecutions: this.executionTimes.length,
|
|
169
|
+
limit: this.options.limit,
|
|
170
|
+
rejectionCount: this.rejectionCount,
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private cleanupOldExecutions(): void {
|
|
176
|
+
const now = Date.now()
|
|
177
|
+
const windowStart = now - this.options.window
|
|
178
|
+
this.executionTimes = this.executionTimes.filter(
|
|
179
|
+
(time) => time > windowStart,
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Resets the rate limiter state
|
|
185
|
+
*/
|
|
186
|
+
reset(): void {
|
|
187
|
+
this.executionTimes = []
|
|
188
|
+
this.executionCount = 0
|
|
189
|
+
this.rejectionCount = 0
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
|
|
195
|
+
*
|
|
196
|
+
* Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
|
|
197
|
+
* - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets
|
|
198
|
+
* - A throttler ensures even spacing between executions, which can be better for consistent performance
|
|
199
|
+
* - A debouncer collapses multiple calls into one, which is better for handling bursts of events
|
|
200
|
+
*
|
|
201
|
+
* Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically
|
|
202
|
+
* need to enforce a hard limit on the number of executions within a time period.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* ```ts
|
|
206
|
+
* // Rate limit to 5 calls per minute
|
|
207
|
+
* const rateLimited = asyncRateLimit(makeApiCall, {
|
|
208
|
+
* limit: 5,
|
|
209
|
+
* window: 60000,
|
|
210
|
+
* onReject: ({ msUntilNextWindow }) => {
|
|
211
|
+
* console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
|
|
212
|
+
* }
|
|
213
|
+
* });
|
|
214
|
+
*
|
|
215
|
+
* // First 5 calls will execute immediately
|
|
216
|
+
* // Additional calls will be rejected until the minute window resets
|
|
217
|
+
* await rateLimited();
|
|
218
|
+
*
|
|
219
|
+
* // For more even execution, consider using throttle instead:
|
|
220
|
+
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
221
|
+
* ```
|
|
222
|
+
*/
|
|
223
|
+
export function asyncRateLimit<
|
|
224
|
+
TFn extends (...args: Array<any>) => Promise<any>,
|
|
225
|
+
>(fn: TFn, initialOptions: Omit<AsyncRateLimiterOptions, 'enabled'>) {
|
|
226
|
+
const rateLimiter = new AsyncRateLimiter(fn, initialOptions)
|
|
227
|
+
return rateLimiter.maybeExecute.bind(rateLimiter)
|
|
228
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for configuring an async throttled function
|
|
3
|
+
*/
|
|
4
|
+
export interface AsyncThrottlerOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
7
|
+
* Defaults to true.
|
|
8
|
+
*/
|
|
9
|
+
enabled?: boolean
|
|
10
|
+
/**
|
|
11
|
+
* Time window in milliseconds during which the function can only be executed once
|
|
12
|
+
* Defaults to 0ms
|
|
13
|
+
*/
|
|
14
|
+
wait: number
|
|
15
|
+
/**
|
|
16
|
+
* Optional error handler for when the throttled function throws
|
|
17
|
+
*/
|
|
18
|
+
onError?: (error: unknown) => void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const defaultOptions: Required<AsyncThrottlerOptions> = {
|
|
22
|
+
enabled: true,
|
|
23
|
+
onError: () => {},
|
|
24
|
+
wait: 0,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A class that creates an async throttled function.
|
|
29
|
+
*
|
|
30
|
+
* Throttling limits how often a function can be executed, allowing only one execution within a specified time window.
|
|
31
|
+
* Unlike debouncing which resets the delay timer on each call, throttling ensures the function executes at a
|
|
32
|
+
* regular interval regardless of how often it's called.
|
|
33
|
+
*
|
|
34
|
+
* This is useful for rate-limiting API calls, handling scroll/resize events, or any scenario where you want to
|
|
35
|
+
* ensure a maximum execution frequency.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* const throttler = new AsyncThrottler(async (value: string) => {
|
|
40
|
+
* await saveToAPI(value);
|
|
41
|
+
* }, { wait: 1000 });
|
|
42
|
+
*
|
|
43
|
+
* // Will only execute once per second no matter how often called
|
|
44
|
+
* inputElement.addEventListener('input', () => {
|
|
45
|
+
* throttler.maybeExecute(inputElement.value);
|
|
46
|
+
* });
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export class AsyncThrottler<
|
|
50
|
+
TFn extends (...args: Array<any>) => Promise<any>,
|
|
51
|
+
TArgs extends Parameters<TFn>,
|
|
52
|
+
> {
|
|
53
|
+
private abortController: AbortController | null = null
|
|
54
|
+
private executionCount = 0
|
|
55
|
+
private isExecuting = false
|
|
56
|
+
private isScheduled = false
|
|
57
|
+
private lastArgs: TArgs | undefined
|
|
58
|
+
private nextExecutionTime = 0
|
|
59
|
+
private options: Required<AsyncThrottlerOptions>
|
|
60
|
+
|
|
61
|
+
constructor(
|
|
62
|
+
private fn: TFn,
|
|
63
|
+
initialOptions: AsyncThrottlerOptions,
|
|
64
|
+
) {
|
|
65
|
+
this.options = {
|
|
66
|
+
...defaultOptions,
|
|
67
|
+
...initialOptions,
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Updates the throttler options
|
|
73
|
+
* Returns the new options state
|
|
74
|
+
*/
|
|
75
|
+
setOptions(
|
|
76
|
+
newOptions: Partial<AsyncThrottlerOptions>,
|
|
77
|
+
): Required<AsyncThrottlerOptions> {
|
|
78
|
+
this.options = {
|
|
79
|
+
...this.options,
|
|
80
|
+
...newOptions,
|
|
81
|
+
}
|
|
82
|
+
return this.options
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Returns the number of times the function has been executed
|
|
87
|
+
*/
|
|
88
|
+
getExecutionCount(): number {
|
|
89
|
+
return this.executionCount
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Returns the next execution time
|
|
94
|
+
*/
|
|
95
|
+
getNextExecutionTime(): number {
|
|
96
|
+
return this.nextExecutionTime
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Cancels any pending execution
|
|
101
|
+
*/
|
|
102
|
+
cancel(): void {
|
|
103
|
+
if (this.abortController) {
|
|
104
|
+
this.abortController.abort()
|
|
105
|
+
this.abortController = null
|
|
106
|
+
}
|
|
107
|
+
this.isScheduled = false
|
|
108
|
+
this.lastArgs = undefined
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Attempts to execute the throttled function
|
|
113
|
+
* If a call is already in progress, it may be blocked or queued depending on the `wait` option
|
|
114
|
+
*/
|
|
115
|
+
async maybeExecute(...args: TArgs): Promise<void> {
|
|
116
|
+
this.lastArgs = args
|
|
117
|
+
if (this.isScheduled) return
|
|
118
|
+
this.isScheduled = true
|
|
119
|
+
|
|
120
|
+
this.abortController = new AbortController()
|
|
121
|
+
const signal = this.abortController.signal
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
while (this.isExecuting) {
|
|
125
|
+
await this.delay(this.options.wait, signal)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
while (Date.now() < this.nextExecutionTime) {
|
|
129
|
+
await this.delay(this.nextExecutionTime - Date.now(), signal)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
this.isScheduled = false
|
|
133
|
+
this.isExecuting = true
|
|
134
|
+
|
|
135
|
+
await this.executeFunction(...this.lastArgs)
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (error instanceof Error && error.name === 'AbortError') {
|
|
138
|
+
return // Silent return on cancellation
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
this.options.onError(error)
|
|
142
|
+
} catch {
|
|
143
|
+
// Ignore errors from error handler
|
|
144
|
+
}
|
|
145
|
+
} finally {
|
|
146
|
+
this.nextExecutionTime = Date.now() + this.options.wait
|
|
147
|
+
this.isExecuting = false
|
|
148
|
+
this.abortController = null
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
153
|
+
return new Promise((resolve, reject) => {
|
|
154
|
+
const timeout = setTimeout(resolve, ms)
|
|
155
|
+
signal.addEventListener(
|
|
156
|
+
'abort',
|
|
157
|
+
() => {
|
|
158
|
+
clearTimeout(timeout)
|
|
159
|
+
reject(new Error('AbortError'))
|
|
160
|
+
},
|
|
161
|
+
{ once: true },
|
|
162
|
+
)
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private async executeFunction(...args: TArgs): Promise<void> {
|
|
167
|
+
if (!this.options.enabled) return
|
|
168
|
+
this.executionCount++
|
|
169
|
+
await this.fn(...args)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Creates an async throttled function that limits how often the function can execute.
|
|
175
|
+
* The throttled function will execute at most once per wait period, even if called multiple times.
|
|
176
|
+
* If called while executing, it will wait until execution completes before scheduling the next call.
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* ```ts
|
|
180
|
+
* const throttled = asyncThrottle(async () => {
|
|
181
|
+
* await someAsyncOperation();
|
|
182
|
+
* }, { wait: 1000 });
|
|
183
|
+
*
|
|
184
|
+
* // This will execute at most once per second
|
|
185
|
+
* await throttled();
|
|
186
|
+
* await throttled(); // Waits 1 second before executing
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
export function asyncThrottle<
|
|
190
|
+
TFn extends (...args: Array<any>) => Promise<any>,
|
|
191
|
+
>(fn: TFn, initialOptions: Omit<AsyncThrottlerOptions, 'enabled'>) {
|
|
192
|
+
const asyncThrottler = new AsyncThrottler(fn, initialOptions)
|
|
193
|
+
return asyncThrottler.maybeExecute.bind(asyncThrottler)
|
|
194
|
+
}
|
package/src/compare.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This function returns `a` if `b` is deeply equal.
|
|
3
|
+
* If not, it will replace any deeply equal children of `b` with those of `a`.
|
|
4
|
+
* This can be used for structural sharing between JSON values for example.
|
|
5
|
+
*/
|
|
6
|
+
export function replaceEqualDeep<T>(a: unknown, b: T): T
|
|
7
|
+
export function replaceEqualDeep(a: any, b: any): any {
|
|
8
|
+
if (a === b) {
|
|
9
|
+
return a
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const array = isPlainArray(a) && isPlainArray(b)
|
|
13
|
+
|
|
14
|
+
if (array || (isPlainObject(a) && isPlainObject(b))) {
|
|
15
|
+
const aItems = array ? a : Object.keys(a)
|
|
16
|
+
const aSize = aItems.length
|
|
17
|
+
const bItems = array ? b : Object.keys(b)
|
|
18
|
+
const bSize = bItems.length
|
|
19
|
+
const copy: any = array ? [] : {}
|
|
20
|
+
|
|
21
|
+
let equalItems = 0
|
|
22
|
+
|
|
23
|
+
for (let i = 0; i < bSize; i++) {
|
|
24
|
+
const key = array ? i : bItems[i]
|
|
25
|
+
if (
|
|
26
|
+
((!array && aItems.includes(key)) || array) &&
|
|
27
|
+
a[key] === undefined &&
|
|
28
|
+
b[key] === undefined
|
|
29
|
+
) {
|
|
30
|
+
copy[key] = undefined
|
|
31
|
+
equalItems++
|
|
32
|
+
} else {
|
|
33
|
+
copy[key] = replaceEqualDeep(a[key], b[key])
|
|
34
|
+
if (copy[key] === a[key] && a[key] !== undefined) {
|
|
35
|
+
equalItems++
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return aSize === bSize && equalItems === aSize ? a : copy
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return b
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Shallow compare objects.
|
|
48
|
+
*/
|
|
49
|
+
export function shallowEqualObjects<T extends Record<string, any>>(
|
|
50
|
+
a: T,
|
|
51
|
+
b: T | undefined,
|
|
52
|
+
): boolean {
|
|
53
|
+
if (!b || Object.keys(a).length !== Object.keys(b).length) {
|
|
54
|
+
return false
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
for (const key in a) {
|
|
58
|
+
if (a[key] !== b[key]) {
|
|
59
|
+
return false
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return true
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function isPlainArray(value: unknown) {
|
|
67
|
+
return Array.isArray(value) && value.length === Object.keys(value).length
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Copied from: https://github.com/jonschlinkert/is-plain-object
|
|
71
|
+
// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
|
|
72
|
+
export function isPlainObject(o: any): o is Object {
|
|
73
|
+
if (!hasObjectPrototype(o)) {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// If has no constructor
|
|
78
|
+
const ctor = o.constructor
|
|
79
|
+
if (ctor === undefined) {
|
|
80
|
+
return true
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// If has modified prototype
|
|
84
|
+
const prot = ctor.prototype
|
|
85
|
+
if (!hasObjectPrototype(prot)) {
|
|
86
|
+
return false
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// If constructor does not have an Object-specific method
|
|
90
|
+
if (!prot.hasOwnProperty('isPrototypeOf')) {
|
|
91
|
+
return false
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Handles Objects created by Object.create(<arbitrary prototype>)
|
|
95
|
+
if (Object.getPrototypeOf(o) !== Object.prototype) {
|
|
96
|
+
return false
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Most likely a plain Object
|
|
100
|
+
return true
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function hasObjectPrototype(o: any): boolean {
|
|
104
|
+
return Object.prototype.toString.call(o) === '[object Object]'
|
|
105
|
+
}
|
package/src/debouncer.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for configuring a debounced function
|
|
3
|
+
*/
|
|
4
|
+
export interface DebouncerOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
7
|
+
* Defaults to true.
|
|
8
|
+
*/
|
|
9
|
+
enabled?: boolean
|
|
10
|
+
/**
|
|
11
|
+
* Whether to execute on the leading edge of the timeout.
|
|
12
|
+
* Defaults to false.
|
|
13
|
+
*/
|
|
14
|
+
leading?: boolean
|
|
15
|
+
/**
|
|
16
|
+
* Whether to execute on the trailing edge of the timeout.
|
|
17
|
+
* Defaults to true.
|
|
18
|
+
*/
|
|
19
|
+
trailing?: boolean
|
|
20
|
+
/**
|
|
21
|
+
* Delay in milliseconds before executing the function
|
|
22
|
+
* Defaults to 0ms
|
|
23
|
+
*/
|
|
24
|
+
wait: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const defaultOptions: Required<DebouncerOptions> = {
|
|
28
|
+
enabled: true,
|
|
29
|
+
leading: false,
|
|
30
|
+
trailing: true,
|
|
31
|
+
wait: 0,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A class that creates a debounced function.
|
|
36
|
+
*
|
|
37
|
+
* Debouncing ensures that a function is only executed after a certain amount of time has passed
|
|
38
|
+
* since its last invocation. This is useful for handling frequent events like window resizing,
|
|
39
|
+
* scroll events, or input changes where you want to limit the rate of execution.
|
|
40
|
+
*
|
|
41
|
+
* The debounced function can be configured to execute either at the start of the delay period
|
|
42
|
+
* (leading edge) or at the end (trailing edge, default). Each new call during the wait period
|
|
43
|
+
* will reset the timer.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const debouncer = new Debouncer((value: string) => {
|
|
48
|
+
* saveToDatabase(value);
|
|
49
|
+
* }, { wait: 500 });
|
|
50
|
+
*
|
|
51
|
+
* // Will only save after 500ms of no new input
|
|
52
|
+
* inputElement.addEventListener('input', () => {
|
|
53
|
+
* debouncer.maybeExecute(inputElement.value);
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export class Debouncer<
|
|
58
|
+
TFn extends (...args: Array<any>) => any,
|
|
59
|
+
TArgs extends Parameters<TFn>,
|
|
60
|
+
> {
|
|
61
|
+
private canLeadingExecute = true
|
|
62
|
+
private executionCount = 0
|
|
63
|
+
private options: Required<DebouncerOptions>
|
|
64
|
+
private timeoutId: NodeJS.Timeout | undefined
|
|
65
|
+
|
|
66
|
+
constructor(
|
|
67
|
+
private fn: TFn,
|
|
68
|
+
initialOptions: DebouncerOptions,
|
|
69
|
+
) {
|
|
70
|
+
this.options = {
|
|
71
|
+
...defaultOptions,
|
|
72
|
+
...initialOptions,
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Updates the debouncer options
|
|
78
|
+
* Returns the new options state
|
|
79
|
+
*/
|
|
80
|
+
setOptions(
|
|
81
|
+
newOptions: Partial<DebouncerOptions>,
|
|
82
|
+
): Required<DebouncerOptions> {
|
|
83
|
+
this.options = {
|
|
84
|
+
...this.options,
|
|
85
|
+
...newOptions,
|
|
86
|
+
}
|
|
87
|
+
return this.options
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Returns the number of times the function has been executed
|
|
92
|
+
*/
|
|
93
|
+
getExecutionCount(): number {
|
|
94
|
+
return this.executionCount
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Attempts to execute the debounced function
|
|
99
|
+
* If a call is already in progress, it will be queued
|
|
100
|
+
*/
|
|
101
|
+
maybeExecute(...args: TArgs): void {
|
|
102
|
+
// Handle leading execution
|
|
103
|
+
if (this.options.leading && this.canLeadingExecute) {
|
|
104
|
+
this.executeFunction(...args)
|
|
105
|
+
this.canLeadingExecute = false
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Clear any existing timeout
|
|
109
|
+
if (this.timeoutId) clearTimeout(this.timeoutId)
|
|
110
|
+
|
|
111
|
+
// Set new timeout that will reset canLeadingExecute
|
|
112
|
+
this.timeoutId = setTimeout(() => {
|
|
113
|
+
this.canLeadingExecute = true
|
|
114
|
+
// Execute trailing only if enabled
|
|
115
|
+
if (this.options.trailing) {
|
|
116
|
+
this.executeFunction(...args)
|
|
117
|
+
}
|
|
118
|
+
}, this.options.wait)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private executeFunction(...args: TArgs): void {
|
|
122
|
+
if (!this.options.enabled) return
|
|
123
|
+
this.executionCount++
|
|
124
|
+
this.fn(...args)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Cancels any pending execution
|
|
129
|
+
*/
|
|
130
|
+
cancel(): void {
|
|
131
|
+
if (this.timeoutId) {
|
|
132
|
+
clearTimeout(this.timeoutId)
|
|
133
|
+
this.canLeadingExecute = true
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Creates a debounced function that delays invoking the provided function until after a specified wait time.
|
|
140
|
+
* Multiple calls during the wait period will cancel previous pending invocations and reset the timer.
|
|
141
|
+
*
|
|
142
|
+
* This the the simple function wrapper implementation pulled from the Debouncer class. If you need
|
|
143
|
+
* more control over the debouncing behavior, use the Debouncer class directly.
|
|
144
|
+
*
|
|
145
|
+
* If leading option is true, the function will execute immediately on the first call, then wait the delay
|
|
146
|
+
* before allowing another execution.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* ```ts
|
|
150
|
+
* const debounced = debounce(() => {
|
|
151
|
+
* saveChanges();
|
|
152
|
+
* }, { wait: 1000 });
|
|
153
|
+
*
|
|
154
|
+
* // Called repeatedly but executes at most once per second
|
|
155
|
+
* inputElement.addEventListener('input', debounced);
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
export function debounce<TFn extends (...args: Array<any>) => any>(
|
|
159
|
+
fn: TFn,
|
|
160
|
+
initialOptions: Omit<DebouncerOptions, 'enabled'>,
|
|
161
|
+
) {
|
|
162
|
+
const debouncer = new Debouncer(fn, initialOptions)
|
|
163
|
+
return debouncer.maybeExecute.bind(debouncer)
|
|
164
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './async-debouncer'
|
|
2
|
+
export * from './async-queuer'
|
|
3
|
+
export * from './async-rate-limiter'
|
|
4
|
+
export * from './async-throttler'
|
|
5
|
+
export * from './compare'
|
|
6
|
+
export * from './debouncer'
|
|
7
|
+
export * from './queuer'
|
|
8
|
+
export * from './rate-limiter'
|
|
9
|
+
export * from './throttler'
|