@tanstack/pacer 0.2.0 → 0.3.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 +78 -45
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +44 -16
- package/dist/cjs/async-queuer.cjs +53 -3
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +28 -3
- package/dist/cjs/async-rate-limiter.cjs +46 -35
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +34 -19
- package/dist/cjs/async-throttler.cjs +85 -57
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +49 -17
- package/dist/cjs/debouncer.cjs +12 -14
- package/dist/cjs/debouncer.cjs.map +1 -1
- package/dist/cjs/debouncer.d.cts +10 -9
- package/dist/cjs/queuer.cjs +51 -1
- package/dist/cjs/queuer.cjs.map +1 -1
- package/dist/cjs/queuer.d.cts +30 -1
- package/dist/cjs/rate-limiter.cjs +1 -5
- package/dist/cjs/rate-limiter.cjs.map +1 -1
- package/dist/cjs/rate-limiter.d.cts +9 -9
- package/dist/cjs/throttler.cjs +29 -36
- package/dist/cjs/throttler.cjs.map +1 -1
- package/dist/cjs/throttler.d.cts +16 -17
- package/dist/cjs/types.d.cts +2 -6
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -1
- package/dist/esm/async-debouncer.d.ts +44 -16
- package/dist/esm/async-debouncer.js +78 -45
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +28 -3
- package/dist/esm/async-queuer.js +53 -3
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +34 -19
- package/dist/esm/async-rate-limiter.js +46 -35
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +49 -17
- package/dist/esm/async-throttler.js +85 -57
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/debouncer.d.ts +10 -9
- package/dist/esm/debouncer.js +12 -14
- package/dist/esm/debouncer.js.map +1 -1
- package/dist/esm/queuer.d.ts +30 -1
- package/dist/esm/queuer.js +51 -1
- package/dist/esm/queuer.js.map +1 -1
- package/dist/esm/rate-limiter.d.ts +9 -9
- package/dist/esm/rate-limiter.js +1 -5
- package/dist/esm/rate-limiter.js.map +1 -1
- package/dist/esm/throttler.d.ts +16 -17
- package/dist/esm/throttler.js +29 -36
- package/dist/esm/throttler.js.map +1 -1
- package/dist/esm/types.d.ts +2 -6
- package/dist/esm/utils.d.ts +1 -1
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/async-debouncer.ts +114 -73
- package/src/async-queuer.ts +93 -8
- package/src/async-rate-limiter.ts +74 -60
- package/src/async-throttler.ts +135 -86
- package/src/debouncer.ts +26 -33
- package/src/queuer.ts +92 -4
- package/src/rate-limiter.ts +14 -26
- package/src/throttler.ts +45 -53
- package/src/types.ts +2 -10
- package/src/utils.ts +1 -1
|
@@ -2,7 +2,7 @@ import { AnyFunction } from './types.cjs';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring a rate-limited function
|
|
4
4
|
*/
|
|
5
|
-
export interface RateLimiterOptions<TFn extends AnyFunction
|
|
5
|
+
export interface RateLimiterOptions<TFn extends AnyFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -15,11 +15,11 @@ export interface RateLimiterOptions<TFn extends AnyFunction, TArgs extends Param
|
|
|
15
15
|
/**
|
|
16
16
|
* Callback function that is called after the function is executed
|
|
17
17
|
*/
|
|
18
|
-
onExecute?: (rateLimiter: RateLimiter<TFn
|
|
18
|
+
onExecute?: (rateLimiter: RateLimiter<TFn>) => void;
|
|
19
19
|
/**
|
|
20
20
|
* Optional callback function that is called when an execution is rejected due to rate limiting
|
|
21
21
|
*/
|
|
22
|
-
onReject?: (rateLimiter: RateLimiter<TFn
|
|
22
|
+
onReject?: (rateLimiter: RateLimiter<TFn>) => void;
|
|
23
23
|
/**
|
|
24
24
|
* Time window in milliseconds within which the limit applies
|
|
25
25
|
*/
|
|
@@ -50,22 +50,22 @@ export interface RateLimiterOptions<TFn extends AnyFunction, TArgs extends Param
|
|
|
50
50
|
* rateLimiter.maybeExecute('123');
|
|
51
51
|
* ```
|
|
52
52
|
*/
|
|
53
|
-
export declare class RateLimiter<TFn extends AnyFunction
|
|
53
|
+
export declare class RateLimiter<TFn extends AnyFunction> {
|
|
54
54
|
private fn;
|
|
55
55
|
private _executionCount;
|
|
56
56
|
private _rejectionCount;
|
|
57
57
|
private _executionTimes;
|
|
58
58
|
private _options;
|
|
59
|
-
constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn
|
|
59
|
+
constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn>);
|
|
60
60
|
/**
|
|
61
61
|
* Updates the rate limiter options
|
|
62
62
|
* Returns the new options state
|
|
63
63
|
*/
|
|
64
|
-
setOptions(newOptions: Partial<RateLimiterOptions<TFn
|
|
64
|
+
setOptions(newOptions: Partial<RateLimiterOptions<TFn>>): void;
|
|
65
65
|
/**
|
|
66
66
|
* Returns the current rate limiter options
|
|
67
67
|
*/
|
|
68
|
-
getOptions(): Required<RateLimiterOptions<TFn
|
|
68
|
+
getOptions(): Required<RateLimiterOptions<TFn>>;
|
|
69
69
|
/**
|
|
70
70
|
* Attempts to execute the rate-limited function if within the configured limits.
|
|
71
71
|
* Will reject execution if the number of calls in the current window exceeds the limit.
|
|
@@ -81,7 +81,7 @@ export declare class RateLimiter<TFn extends AnyFunction, TArgs extends Paramete
|
|
|
81
81
|
* rateLimiter.maybeExecute('arg1', 'arg2'); // false
|
|
82
82
|
* ```
|
|
83
83
|
*/
|
|
84
|
-
maybeExecute(...args:
|
|
84
|
+
maybeExecute(...args: Parameters<TFn>): boolean;
|
|
85
85
|
private executeFunction;
|
|
86
86
|
private rejectFunction;
|
|
87
87
|
private cleanupOldExecutions;
|
|
@@ -136,4 +136,4 @@ export declare class RateLimiter<TFn extends AnyFunction, TArgs extends Paramete
|
|
|
136
136
|
* const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
|
|
137
137
|
* ```
|
|
138
138
|
*/
|
|
139
|
-
export declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<RateLimiterOptions<TFn
|
|
139
|
+
export declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<RateLimiterOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => boolean;
|
package/dist/cjs/throttler.cjs
CHANGED
|
@@ -3,17 +3,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
const defaultOptions = {
|
|
4
4
|
enabled: true,
|
|
5
5
|
leading: true,
|
|
6
|
-
trailing: true,
|
|
7
|
-
wait: 0,
|
|
8
6
|
onExecute: () => {
|
|
9
|
-
}
|
|
7
|
+
},
|
|
8
|
+
trailing: true,
|
|
9
|
+
wait: 0
|
|
10
10
|
};
|
|
11
11
|
class Throttler {
|
|
12
12
|
constructor(fn, initialOptions) {
|
|
13
13
|
this.fn = fn;
|
|
14
14
|
this._executionCount = 0;
|
|
15
15
|
this._lastExecutionTime = 0;
|
|
16
|
-
this._isPending = false;
|
|
17
16
|
this._options = {
|
|
18
17
|
...defaultOptions,
|
|
19
18
|
...initialOptions
|
|
@@ -24,11 +23,10 @@ class Throttler {
|
|
|
24
23
|
* Returns the new options state
|
|
25
24
|
*/
|
|
26
25
|
setOptions(newOptions) {
|
|
27
|
-
this._options = {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
return this._options;
|
|
26
|
+
this._options = { ...this._options, ...newOptions };
|
|
27
|
+
if (!this._options.enabled) {
|
|
28
|
+
this.cancel();
|
|
29
|
+
}
|
|
32
30
|
}
|
|
33
31
|
/**
|
|
34
32
|
* Returns the current throttler options
|
|
@@ -61,26 +59,18 @@ class Throttler {
|
|
|
61
59
|
maybeExecute(...args) {
|
|
62
60
|
const now = Date.now();
|
|
63
61
|
const timeSinceLastExecution = now - this._lastExecutionTime;
|
|
64
|
-
if (timeSinceLastExecution >= this._options.wait) {
|
|
65
|
-
|
|
66
|
-
this.executeFunction(...args);
|
|
67
|
-
}
|
|
68
|
-
this._lastExecutionTime = now;
|
|
69
|
-
this._isPending = false;
|
|
62
|
+
if (this._options.leading && timeSinceLastExecution >= this._options.wait) {
|
|
63
|
+
this.executeFunction(...args);
|
|
70
64
|
} else {
|
|
71
65
|
this._lastArgs = args;
|
|
72
66
|
if (!this._timeoutId && this._options.trailing) {
|
|
73
|
-
this.
|
|
67
|
+
const _timeSinceLastExecution = this._lastExecutionTime ? now - this._lastExecutionTime : 0;
|
|
68
|
+
const timeoutDuration = this._options.wait - _timeSinceLastExecution;
|
|
74
69
|
this._timeoutId = setTimeout(() => {
|
|
75
|
-
if (this._lastArgs) {
|
|
70
|
+
if (this._lastArgs !== void 0) {
|
|
76
71
|
this.executeFunction(...this._lastArgs);
|
|
77
|
-
this._lastArgs = void 0;
|
|
78
72
|
}
|
|
79
|
-
|
|
80
|
-
this._timeoutId = void 0;
|
|
81
|
-
this._isPending = false;
|
|
82
|
-
this._options.onExecute(this);
|
|
83
|
-
}, this._options.wait - timeSinceLastExecution);
|
|
73
|
+
}, timeoutDuration);
|
|
84
74
|
}
|
|
85
75
|
}
|
|
86
76
|
}
|
|
@@ -88,6 +78,10 @@ class Throttler {
|
|
|
88
78
|
if (!this._options.enabled) return;
|
|
89
79
|
this.fn(...args);
|
|
90
80
|
this._executionCount++;
|
|
81
|
+
this._lastExecutionTime = Date.now();
|
|
82
|
+
this._timeoutId = void 0;
|
|
83
|
+
this._lastArgs = void 0;
|
|
84
|
+
this._options.onExecute(this);
|
|
91
85
|
}
|
|
92
86
|
/**
|
|
93
87
|
* Cancels any pending trailing execution and clears internal state.
|
|
@@ -103,21 +97,8 @@ class Throttler {
|
|
|
103
97
|
clearTimeout(this._timeoutId);
|
|
104
98
|
this._timeoutId = void 0;
|
|
105
99
|
this._lastArgs = void 0;
|
|
106
|
-
this._isPending = false;
|
|
107
100
|
}
|
|
108
101
|
}
|
|
109
|
-
/**
|
|
110
|
-
* Returns the number of times the function has been executed
|
|
111
|
-
*/
|
|
112
|
-
getExecutionCount() {
|
|
113
|
-
return this._executionCount;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Returns `true` if there is a pending execution
|
|
117
|
-
*/
|
|
118
|
-
getIsPending() {
|
|
119
|
-
return this._options.enabled && this._isPending;
|
|
120
|
-
}
|
|
121
102
|
/**
|
|
122
103
|
* Returns the last execution time
|
|
123
104
|
*/
|
|
@@ -130,6 +111,18 @@ class Throttler {
|
|
|
130
111
|
getNextExecutionTime() {
|
|
131
112
|
return this._lastExecutionTime + this._options.wait;
|
|
132
113
|
}
|
|
114
|
+
/**
|
|
115
|
+
* Returns the number of times the function has been executed
|
|
116
|
+
*/
|
|
117
|
+
getExecutionCount() {
|
|
118
|
+
return this._executionCount;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Returns `true` if there is a pending execution
|
|
122
|
+
*/
|
|
123
|
+
getIsPending() {
|
|
124
|
+
return this._options.enabled && !!this._timeoutId;
|
|
125
|
+
}
|
|
133
126
|
}
|
|
134
127
|
function throttle(fn, initialOptions) {
|
|
135
128
|
const throttler = new Throttler(fn, initialOptions);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions
|
|
1
|
+
{"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["import 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 * Defaults to true.\n */\n enabled?: 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 */\n wait: 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 * Returns the new options state\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 * 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\n // Handle leading execution\n if (this._options.leading && timeSinceLastExecution >= this._options.wait) {\n this.executeFunction(...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 = this._options.wait - _timeSinceLastExecution\n this._timeoutId = setTimeout(() => {\n if (this._lastArgs !== undefined) {\n this.executeFunction(...this._lastArgs)\n }\n }, timeoutDuration)\n }\n }\n }\n\n private executeFunction(...args: Parameters<TFn>): void {\n if (!this._options.enabled) 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._options.wait\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._options.enabled && !!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: Omit<ThrottlerOptions<TFn>, 'enabled'>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":[],"mappings":";;AA+BA,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;AAAA,EAOF,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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyBd,gBAAgB,MAA6B;AACrC,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,yBAAyB,MAAM,KAAK;AAG1C,QAAI,KAAK,SAAS,WAAW,0BAA0B,KAAK,SAAS,MAAM;AACpE,WAAA,gBAAgB,GAAG,IAAI;AAAA,IAAA,OACvB;AAEL,WAAK,YAAY;AAGjB,UAAI,CAAC,KAAK,cAAc,KAAK,SAAS,UAAU;AAC9C,cAAM,0BAA0B,KAAK,qBACjC,MAAM,KAAK,qBACX;AACE,cAAA,kBAAkB,KAAK,SAAS,OAAO;AACxC,aAAA,aAAa,WAAW,MAAM;AAC7B,cAAA,KAAK,cAAc,QAAW;AAC3B,iBAAA,gBAAgB,GAAG,KAAK,SAAS;AAAA,UAAA;AAAA,WAEvC,eAAe;AAAA,MAAA;AAAA,IACpB;AAAA,EACF;AAAA,EAGM,mBAAmB,MAA6B;AAClD,QAAA,CAAC,KAAK,SAAS,QAAS;AACvB,SAAA,GAAG,GAAG,IAAI;AACV,SAAA;AACA,SAAA,qBAAqB,KAAK,IAAI;AACnC,SAAK,aAAa;AAClB,SAAK,YAAY;AACZ,SAAA,SAAS,UAAU,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAY9B,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAClB,WAAK,YAAY;AAAA,IAAA;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAMF,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AACtB,WAAA,KAAK,qBAAqB,KAAK,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMjD,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACtB,WAAO,KAAK,SAAS,WAAW,CAAC,CAAC,KAAK;AAAA,EAAA;AAE3C;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
|
@@ -2,7 +2,7 @@ import { AnyFunction } from './types.cjs';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring a throttled function
|
|
4
4
|
*/
|
|
5
|
-
export interface ThrottlerOptions<TFn extends AnyFunction
|
|
5
|
+
export interface ThrottlerOptions<TFn extends AnyFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -16,7 +16,7 @@ export interface ThrottlerOptions<TFn extends AnyFunction, TArgs extends Paramet
|
|
|
16
16
|
/**
|
|
17
17
|
* Callback function that is called after the function is executed
|
|
18
18
|
*/
|
|
19
|
-
onExecute?: (throttler: Throttler<TFn
|
|
19
|
+
onExecute?: (throttler: Throttler<TFn>) => void;
|
|
20
20
|
/**
|
|
21
21
|
* Whether to execute on the trailing edge of the timeout.
|
|
22
22
|
* Defaults to true.
|
|
@@ -54,24 +54,23 @@ export interface ThrottlerOptions<TFn extends AnyFunction, TArgs extends Paramet
|
|
|
54
54
|
* throttler.maybeExecute('123'); // Throttled
|
|
55
55
|
* ```
|
|
56
56
|
*/
|
|
57
|
-
export declare class Throttler<TFn extends AnyFunction
|
|
57
|
+
export declare class Throttler<TFn extends AnyFunction> {
|
|
58
58
|
private fn;
|
|
59
59
|
private _executionCount;
|
|
60
60
|
private _lastArgs;
|
|
61
61
|
private _lastExecutionTime;
|
|
62
62
|
private _options;
|
|
63
63
|
private _timeoutId;
|
|
64
|
-
|
|
65
|
-
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn, TArgs>);
|
|
64
|
+
constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn>);
|
|
66
65
|
/**
|
|
67
66
|
* Updates the throttler options
|
|
68
67
|
* Returns the new options state
|
|
69
68
|
*/
|
|
70
|
-
setOptions(newOptions: Partial<ThrottlerOptions<TFn
|
|
69
|
+
setOptions(newOptions: Partial<ThrottlerOptions<TFn>>): void;
|
|
71
70
|
/**
|
|
72
71
|
* Returns the current throttler options
|
|
73
72
|
*/
|
|
74
|
-
getOptions(): Required<ThrottlerOptions<TFn
|
|
73
|
+
getOptions(): Required<ThrottlerOptions<TFn>>;
|
|
75
74
|
/**
|
|
76
75
|
* Attempts to execute the throttled function. The execution behavior depends on the throttler options:
|
|
77
76
|
*
|
|
@@ -94,7 +93,7 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
94
93
|
* throttled.maybeExecute('c', 'd');
|
|
95
94
|
* ```
|
|
96
95
|
*/
|
|
97
|
-
maybeExecute(...args:
|
|
96
|
+
maybeExecute(...args: Parameters<TFn>): void;
|
|
98
97
|
private executeFunction;
|
|
99
98
|
/**
|
|
100
99
|
* Cancels any pending trailing execution and clears internal state.
|
|
@@ -106,14 +105,6 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
106
105
|
* Has no effect if there is no pending execution.
|
|
107
106
|
*/
|
|
108
107
|
cancel(): void;
|
|
109
|
-
/**
|
|
110
|
-
* Returns the number of times the function has been executed
|
|
111
|
-
*/
|
|
112
|
-
getExecutionCount(): number;
|
|
113
|
-
/**
|
|
114
|
-
* Returns `true` if there is a pending execution
|
|
115
|
-
*/
|
|
116
|
-
getIsPending(): boolean;
|
|
117
108
|
/**
|
|
118
109
|
* Returns the last execution time
|
|
119
110
|
*/
|
|
@@ -122,6 +113,14 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
122
113
|
* Returns the next execution time
|
|
123
114
|
*/
|
|
124
115
|
getNextExecutionTime(): number;
|
|
116
|
+
/**
|
|
117
|
+
* Returns the number of times the function has been executed
|
|
118
|
+
*/
|
|
119
|
+
getExecutionCount(): number;
|
|
120
|
+
/**
|
|
121
|
+
* Returns `true` if there is a pending execution
|
|
122
|
+
*/
|
|
123
|
+
getIsPending(): boolean;
|
|
125
124
|
}
|
|
126
125
|
/**
|
|
127
126
|
* Creates a throttled function that limits how often the provided function can execute.
|
|
@@ -149,4 +148,4 @@ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters
|
|
|
149
148
|
* });
|
|
150
149
|
* ```
|
|
151
150
|
*/
|
|
152
|
-
export declare function throttle<TFn extends AnyFunction
|
|
151
|
+
export declare function throttle<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<ThrottlerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => void;
|
package/dist/cjs/types.d.cts
CHANGED
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Represents a function that can be called with any arguments and returns any value.
|
|
3
|
-
* @template TArgs - The type of the arguments the function can be called with.
|
|
4
|
-
* @returns The return value of the function.
|
|
5
3
|
*/
|
|
6
|
-
export type AnyFunction
|
|
4
|
+
export type AnyFunction = (...args: Array<any>) => any;
|
|
7
5
|
/**
|
|
8
6
|
* Represents an asynchronous function that can be called with any arguments and returns a promise.
|
|
9
|
-
* @template TArgs - The type of the arguments the function can be called with.
|
|
10
|
-
* @returns A promise that resolves to the return value of the function.
|
|
11
7
|
*/
|
|
12
|
-
export type AnyAsyncFunction
|
|
8
|
+
export type AnyAsyncFunction = (...args: Array<any>) => Promise<any>;
|
package/dist/cjs/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["export function bindInstanceMethods<T extends Record<string, any>>(\n instance: T,\n) {\n return Object.getOwnPropertyNames(Object.getPrototypeOf(instance))\n .filter((key) => typeof instance[key as keyof T] === 'function')\n .reduce((acc: any, key) => {\n const method = instance[key as keyof T]\n if (typeof method === 'function') {\n acc[key] = method.bind(instance)\n }\n return acc\n }, {} as T)\n}\n"],"names":[],"mappings":";;AAAO,SAAS,oBACd,
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["export function bindInstanceMethods<T extends Record<string, any>>(\n instance: T,\n): T {\n return Object.getOwnPropertyNames(Object.getPrototypeOf(instance))\n .filter((key) => typeof instance[key as keyof T] === 'function')\n .reduce((acc: any, key) => {\n const method = instance[key as keyof T]\n if (typeof method === 'function') {\n acc[key] = method.bind(instance)\n }\n return acc\n }, {} as T)\n}\n"],"names":[],"mappings":";;AAAO,SAAS,oBACd,UACG;AACH,SAAO,OAAO,oBAAoB,OAAO,eAAe,QAAQ,CAAC,EAC9D,OAAO,CAAC,QAAQ,OAAO,SAAS,GAAc,MAAM,UAAU,EAC9D,OAAO,CAAC,KAAU,QAAQ;AACnB,UAAA,SAAS,SAAS,GAAc;AAClC,QAAA,OAAO,WAAW,YAAY;AAChC,UAAI,GAAG,IAAI,OAAO,KAAK,QAAQ;AAAA,IAAA;AAE1B,WAAA;AAAA,EACT,GAAG,EAAO;AACd;;"}
|
package/dist/cjs/utils.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function bindInstanceMethods<T extends Record<string, any>>(instance: T):
|
|
1
|
+
export declare function bindInstanceMethods<T extends Record<string, any>>(instance: T): T;
|
|
@@ -2,7 +2,7 @@ import { AnyAsyncFunction } from './types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Options for configuring an async debounced function
|
|
4
4
|
*/
|
|
5
|
-
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction
|
|
5
|
+
export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
6
6
|
/**
|
|
7
7
|
* Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.
|
|
8
8
|
* Defaults to true.
|
|
@@ -16,11 +16,15 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
16
16
|
/**
|
|
17
17
|
* Optional error handler for when the debounced function throws
|
|
18
18
|
*/
|
|
19
|
-
onError?: (error: unknown) => void;
|
|
19
|
+
onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
|
|
20
20
|
/**
|
|
21
|
-
* Optional
|
|
21
|
+
* Optional callback to call when the debounced function is executed
|
|
22
22
|
*/
|
|
23
|
-
|
|
23
|
+
onSettled?: (debouncer: AsyncDebouncer<TFn>) => void;
|
|
24
|
+
/**
|
|
25
|
+
* Optional callback to call when the debounced function is executed
|
|
26
|
+
*/
|
|
27
|
+
onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
|
|
24
28
|
/**
|
|
25
29
|
* Whether to execute on the trailing edge of the timeout.
|
|
26
30
|
* Defaults to true.
|
|
@@ -54,43 +58,67 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction, TArgs exten
|
|
|
54
58
|
* });
|
|
55
59
|
* ```
|
|
56
60
|
*/
|
|
57
|
-
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction
|
|
61
|
+
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
58
62
|
private fn;
|
|
59
63
|
private _abortController;
|
|
60
|
-
private
|
|
64
|
+
private _canLeadingExecute;
|
|
65
|
+
private _errorCount;
|
|
61
66
|
private _isExecuting;
|
|
67
|
+
private _isPending;
|
|
62
68
|
private _lastArgs;
|
|
69
|
+
private _lastResult;
|
|
63
70
|
private _options;
|
|
71
|
+
private _settleCount;
|
|
72
|
+
private _successCount;
|
|
64
73
|
private _timeoutId;
|
|
65
|
-
|
|
66
|
-
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn, TArgs>);
|
|
74
|
+
constructor(fn: TFn, initialOptions: AsyncDebouncerOptions<TFn>);
|
|
67
75
|
/**
|
|
68
76
|
* Updates the debouncer options
|
|
69
77
|
* Returns the new options state
|
|
70
78
|
*/
|
|
71
|
-
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn
|
|
79
|
+
setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void;
|
|
72
80
|
/**
|
|
73
81
|
* Returns the current debouncer options
|
|
74
82
|
*/
|
|
75
|
-
getOptions(): Required<AsyncDebouncerOptions<TFn
|
|
83
|
+
getOptions(): Required<AsyncDebouncerOptions<TFn>>;
|
|
76
84
|
/**
|
|
77
85
|
* Attempts to execute the debounced function
|
|
78
86
|
* If a call is already in progress, it will be queued
|
|
79
87
|
*/
|
|
80
|
-
maybeExecute(...args:
|
|
88
|
+
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
81
89
|
private executeFunction;
|
|
82
90
|
/**
|
|
83
|
-
*
|
|
91
|
+
* Cancel without resetting _canLeadingExecute
|
|
92
|
+
*/
|
|
93
|
+
private _cancel;
|
|
94
|
+
/**
|
|
95
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
84
96
|
*/
|
|
85
97
|
cancel(): void;
|
|
86
98
|
/**
|
|
87
|
-
* Returns the
|
|
99
|
+
* Returns the last result of the debounced function
|
|
100
|
+
*/
|
|
101
|
+
getLastResult(): ReturnType<TFn> | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Returns the number of times the function has been executed successfully
|
|
104
|
+
*/
|
|
105
|
+
getSuccessCount(): number;
|
|
106
|
+
/**
|
|
107
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
88
108
|
*/
|
|
89
|
-
|
|
109
|
+
getSettleCount(): number;
|
|
90
110
|
/**
|
|
91
|
-
* Returns
|
|
111
|
+
* Returns the number of times the function has errored
|
|
112
|
+
*/
|
|
113
|
+
getErrorCount(): number;
|
|
114
|
+
/**
|
|
115
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
92
116
|
*/
|
|
93
117
|
getIsPending(): boolean;
|
|
118
|
+
/**
|
|
119
|
+
* Returns `true` if there is currently an execution in progress
|
|
120
|
+
*/
|
|
121
|
+
getIsExecuting(): boolean;
|
|
94
122
|
}
|
|
95
123
|
/**
|
|
96
124
|
* Creates an async debounced function that delays execution until after a specified wait time.
|
|
@@ -109,4 +137,4 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction, TArgs extends
|
|
|
109
137
|
* await debounced("third"); // Executes after 1s
|
|
110
138
|
* ```
|
|
111
139
|
*/
|
|
112
|
-
export declare function asyncDebounce<TFn extends AnyAsyncFunction
|
|
140
|
+
export declare function asyncDebounce<TFn extends AnyAsyncFunction>(fn: TFn, initialOptions: Omit<AsyncDebouncerOptions<TFn>, 'enabled'>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn> | undefined>;
|
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
const defaultOptions = {
|
|
2
2
|
enabled: true,
|
|
3
3
|
leading: false,
|
|
4
|
-
trailing: true,
|
|
5
4
|
onError: () => {
|
|
6
5
|
},
|
|
7
|
-
|
|
6
|
+
onSettled: () => {
|
|
7
|
+
},
|
|
8
|
+
onSuccess: () => {
|
|
8
9
|
},
|
|
10
|
+
trailing: true,
|
|
9
11
|
wait: 0
|
|
10
12
|
};
|
|
11
13
|
class AsyncDebouncer {
|
|
12
14
|
constructor(fn, initialOptions) {
|
|
13
15
|
this.fn = fn;
|
|
14
16
|
this._abortController = null;
|
|
15
|
-
this.
|
|
17
|
+
this._canLeadingExecute = true;
|
|
18
|
+
this._errorCount = 0;
|
|
16
19
|
this._isExecuting = false;
|
|
20
|
+
this._isPending = false;
|
|
21
|
+
this._settleCount = 0;
|
|
22
|
+
this._successCount = 0;
|
|
17
23
|
this._timeoutId = null;
|
|
18
|
-
this._canLeadingExecute = true;
|
|
19
24
|
this._options = {
|
|
20
25
|
...defaultOptions,
|
|
21
26
|
...initialOptions
|
|
@@ -26,11 +31,10 @@ class AsyncDebouncer {
|
|
|
26
31
|
* Returns the new options state
|
|
27
32
|
*/
|
|
28
33
|
setOptions(newOptions) {
|
|
29
|
-
this._options = {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
return this._options;
|
|
34
|
+
this._options = { ...this._options, ...newOptions };
|
|
35
|
+
if (!this._options.enabled) {
|
|
36
|
+
this._isPending = false;
|
|
37
|
+
}
|
|
34
38
|
}
|
|
35
39
|
/**
|
|
36
40
|
* Returns the current debouncer options
|
|
@@ -43,53 +47,50 @@ class AsyncDebouncer {
|
|
|
43
47
|
* If a call is already in progress, it will be queued
|
|
44
48
|
*/
|
|
45
49
|
async maybeExecute(...args) {
|
|
46
|
-
this.
|
|
50
|
+
this._cancel();
|
|
47
51
|
this._lastArgs = args;
|
|
48
52
|
if (this._options.leading && this._canLeadingExecute) {
|
|
49
53
|
this._canLeadingExecute = false;
|
|
50
54
|
await this.executeFunction(...args);
|
|
55
|
+
return this._lastResult;
|
|
56
|
+
}
|
|
57
|
+
if (this._options.trailing) {
|
|
58
|
+
this._isPending = true;
|
|
51
59
|
}
|
|
52
60
|
return new Promise((resolve) => {
|
|
53
61
|
this._timeoutId = setTimeout(async () => {
|
|
54
|
-
if (this.
|
|
55
|
-
|
|
56
|
-
return;
|
|
62
|
+
if (this._options.trailing && this._lastArgs) {
|
|
63
|
+
await this.executeFunction(...this._lastArgs);
|
|
57
64
|
}
|
|
58
65
|
this._canLeadingExecute = true;
|
|
59
|
-
|
|
60
|
-
this._abortController = new AbortController();
|
|
61
|
-
try {
|
|
62
|
-
this._isExecuting = true;
|
|
63
|
-
if (this._lastArgs) {
|
|
64
|
-
await this.executeFunction(...this._lastArgs);
|
|
65
|
-
}
|
|
66
|
-
} catch (error) {
|
|
67
|
-
try {
|
|
68
|
-
this._options.onError(error);
|
|
69
|
-
} catch {
|
|
70
|
-
console.error("Error in error handler", error);
|
|
71
|
-
}
|
|
72
|
-
} finally {
|
|
73
|
-
this._isExecuting = false;
|
|
74
|
-
this._abortController = null;
|
|
75
|
-
resolve();
|
|
76
|
-
}
|
|
77
|
-
} else {
|
|
78
|
-
resolve();
|
|
79
|
-
}
|
|
66
|
+
resolve(this._lastResult);
|
|
80
67
|
}, this._options.wait);
|
|
81
68
|
});
|
|
82
69
|
}
|
|
83
70
|
async executeFunction(...args) {
|
|
84
|
-
if (!this._options.enabled) return;
|
|
85
|
-
this.
|
|
86
|
-
|
|
87
|
-
|
|
71
|
+
if (!this._options.enabled) return void 0;
|
|
72
|
+
this._abortController = new AbortController();
|
|
73
|
+
try {
|
|
74
|
+
this._isExecuting = true;
|
|
75
|
+
this._lastResult = await this.fn(...args);
|
|
76
|
+
this._successCount++;
|
|
77
|
+
this._options.onSuccess(this._lastResult, this);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
this._errorCount++;
|
|
80
|
+
this._options.onError(error, this);
|
|
81
|
+
} finally {
|
|
82
|
+
this._isExecuting = false;
|
|
83
|
+
this._isPending = false;
|
|
84
|
+
this._settleCount++;
|
|
85
|
+
this._abortController = null;
|
|
86
|
+
this._options.onSettled(this);
|
|
87
|
+
}
|
|
88
|
+
return this._lastResult;
|
|
88
89
|
}
|
|
89
90
|
/**
|
|
90
|
-
*
|
|
91
|
+
* Cancel without resetting _canLeadingExecute
|
|
91
92
|
*/
|
|
92
|
-
|
|
93
|
+
_cancel() {
|
|
93
94
|
if (this._timeoutId) {
|
|
94
95
|
clearTimeout(this._timeoutId);
|
|
95
96
|
this._timeoutId = null;
|
|
@@ -99,19 +100,51 @@ class AsyncDebouncer {
|
|
|
99
100
|
this._abortController = null;
|
|
100
101
|
}
|
|
101
102
|
this._lastArgs = void 0;
|
|
103
|
+
this._isPending = false;
|
|
104
|
+
this._isExecuting = false;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Cancels any pending execution or aborts any execution in progress
|
|
108
|
+
*/
|
|
109
|
+
cancel() {
|
|
102
110
|
this._canLeadingExecute = true;
|
|
111
|
+
this._cancel();
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Returns the last result of the debounced function
|
|
115
|
+
*/
|
|
116
|
+
getLastResult() {
|
|
117
|
+
return this._lastResult;
|
|
103
118
|
}
|
|
104
119
|
/**
|
|
105
|
-
* Returns the number of times the function has been executed
|
|
120
|
+
* Returns the number of times the function has been executed successfully
|
|
106
121
|
*/
|
|
107
|
-
|
|
108
|
-
return this.
|
|
122
|
+
getSuccessCount() {
|
|
123
|
+
return this._successCount;
|
|
109
124
|
}
|
|
110
125
|
/**
|
|
111
|
-
* Returns
|
|
126
|
+
* Returns the number of times the function has settled (completed or errored)
|
|
127
|
+
*/
|
|
128
|
+
getSettleCount() {
|
|
129
|
+
return this._settleCount;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Returns the number of times the function has errored
|
|
133
|
+
*/
|
|
134
|
+
getErrorCount() {
|
|
135
|
+
return this._errorCount;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Returns `true` if there is a pending execution queued up for trailing execution
|
|
112
139
|
*/
|
|
113
140
|
getIsPending() {
|
|
114
|
-
return this._options.enabled &&
|
|
141
|
+
return this._options.enabled && this._isPending;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Returns `true` if there is currently an execution in progress
|
|
145
|
+
*/
|
|
146
|
+
getIsExecuting() {
|
|
147
|
+
return this._isExecuting;
|
|
115
148
|
}
|
|
116
149
|
}
|
|
117
150
|
function asyncDebounce(fn, initialOptions) {
|