@tanstack/pacer 0.1.0 → 0.2.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 (74) hide show
  1. package/dist/cjs/async-debouncer.cjs +60 -44
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +37 -24
  4. package/dist/cjs/async-queuer.cjs +149 -125
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +65 -48
  7. package/dist/cjs/async-rate-limiter.cjs +63 -46
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +39 -27
  10. package/dist/cjs/async-throttler.cjs +70 -47
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +43 -25
  13. package/dist/cjs/debouncer.cjs +46 -22
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +25 -11
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/index.d.cts +2 -0
  19. package/dist/cjs/queuer.cjs +114 -104
  20. package/dist/cjs/queuer.cjs.map +1 -1
  21. package/dist/cjs/queuer.d.cts +53 -40
  22. package/dist/cjs/rate-limiter.cjs +54 -42
  23. package/dist/cjs/rate-limiter.cjs.map +1 -1
  24. package/dist/cjs/rate-limiter.d.cts +37 -45
  25. package/dist/cjs/throttler.cjs +61 -41
  26. package/dist/cjs/throttler.cjs.map +1 -1
  27. package/dist/cjs/throttler.d.cts +35 -22
  28. package/dist/cjs/types.d.cts +12 -0
  29. package/dist/cjs/utils.cjs +13 -0
  30. package/dist/cjs/utils.cjs.map +1 -0
  31. package/dist/cjs/utils.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +37 -24
  33. package/dist/esm/async-debouncer.js +60 -44
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +65 -48
  36. package/dist/esm/async-queuer.js +149 -125
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +39 -27
  39. package/dist/esm/async-rate-limiter.js +63 -46
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +43 -25
  42. package/dist/esm/async-throttler.js +70 -47
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/debouncer.d.ts +25 -11
  45. package/dist/esm/debouncer.js +46 -22
  46. package/dist/esm/debouncer.js.map +1 -1
  47. package/dist/esm/index.d.ts +2 -0
  48. package/dist/esm/index.js +2 -0
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/queuer.d.ts +53 -40
  51. package/dist/esm/queuer.js +114 -104
  52. package/dist/esm/queuer.js.map +1 -1
  53. package/dist/esm/rate-limiter.d.ts +37 -45
  54. package/dist/esm/rate-limiter.js +54 -42
  55. package/dist/esm/rate-limiter.js.map +1 -1
  56. package/dist/esm/throttler.d.ts +35 -22
  57. package/dist/esm/throttler.js +61 -41
  58. package/dist/esm/throttler.js.map +1 -1
  59. package/dist/esm/types.d.ts +12 -0
  60. package/dist/esm/utils.d.ts +1 -0
  61. package/dist/esm/utils.js +13 -0
  62. package/dist/esm/utils.js.map +1 -0
  63. package/package.json +8 -1
  64. package/src/async-debouncer.ts +90 -62
  65. package/src/async-queuer.ts +178 -145
  66. package/src/async-rate-limiter.ts +93 -67
  67. package/src/async-throttler.ts +98 -63
  68. package/src/debouncer.ts +71 -35
  69. package/src/index.ts +2 -0
  70. package/src/queuer.ts +135 -118
  71. package/src/rate-limiter.ts +79 -81
  72. package/src/throttler.ts +87 -61
  73. package/src/types.ts +17 -0
  74. package/src/utils.ts +13 -0
@@ -3,15 +3,19 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const defaultOptions = {
4
4
  enabled: true,
5
5
  limit: 1,
6
+ onExecute: () => {
7
+ },
8
+ onReject: () => {
9
+ },
6
10
  window: 0
7
11
  };
8
12
  class RateLimiter {
9
13
  constructor(fn, initialOptions) {
10
14
  this.fn = fn;
11
- this.executionCount = 0;
12
- this.rejectionCount = 0;
13
- this.executionTimes = [];
14
- this.options = {
15
+ this._executionCount = 0;
16
+ this._rejectionCount = 0;
17
+ this._executionTimes = [];
18
+ this._options = {
15
19
  ...defaultOptions,
16
20
  ...initialOptions
17
21
  };
@@ -21,30 +25,17 @@ class RateLimiter {
21
25
  * Returns the new options state
22
26
  */
23
27
  setOptions(newOptions) {
24
- this.options = {
25
- ...this.options,
28
+ this._options = {
29
+ ...this._options,
26
30
  ...newOptions
27
31
  };
28
- return this.options;
32
+ return this._options;
29
33
  }
30
34
  /**
31
- * Returns the number of times the function has been executed
32
- */
33
- getExecutionCount() {
34
- return this.executionCount;
35
- }
36
- /**
37
- * Returns the number of times the function has been rejected
38
- */
39
- getRejectionCount() {
40
- return this.rejectionCount;
41
- }
42
- /**
43
- * Returns the number of remaining executions allowed in the current window
35
+ * Returns the current rate limiter options
44
36
  */
45
- getRemainingInWindow() {
46
- this.cleanupOldExecutions();
47
- return Math.max(0, this.options.limit - this.executionTimes.length);
37
+ getOptions() {
38
+ return this._options;
48
39
  }
49
40
  /**
50
41
  * Attempts to execute the rate-limited function if within the configured limits.
@@ -63,7 +54,7 @@ class RateLimiter {
63
54
  */
64
55
  maybeExecute(...args) {
65
56
  this.cleanupOldExecutions();
66
- if (this.executionTimes.length < this.options.limit) {
57
+ if (this._executionTimes.length < this._options.limit) {
67
58
  this.executeFunction(...args);
68
59
  return true;
69
60
  }
@@ -71,39 +62,60 @@ class RateLimiter {
71
62
  return false;
72
63
  }
73
64
  executeFunction(...args) {
74
- if (!this.options.enabled) return;
65
+ var _a, _b;
66
+ if (!this._options.enabled) return;
75
67
  const now = Date.now();
76
- this.executionCount++;
77
- this.executionTimes.push(now);
68
+ this._executionCount++;
69
+ this._executionTimes.push(now);
78
70
  this.fn(...args);
71
+ (_b = (_a = this._options).onExecute) == null ? void 0 : _b.call(_a, this);
79
72
  }
80
73
  rejectFunction() {
81
- this.rejectionCount++;
82
- if (this.options.onReject) {
83
- const oldestExecution = Math.min(...this.executionTimes);
84
- const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
85
- this.options.onReject({
86
- msUntilNextWindow,
87
- currentExecutions: this.executionTimes.length,
88
- limit: this.options.limit,
89
- rejectionCount: this.rejectionCount
90
- });
74
+ this._rejectionCount++;
75
+ if (this._options.onReject) {
76
+ this._options.onReject(this);
91
77
  }
92
78
  }
93
79
  cleanupOldExecutions() {
94
80
  const now = Date.now();
95
- const windowStart = now - this.options.window;
96
- this.executionTimes = this.executionTimes.filter(
81
+ const windowStart = now - this._options.window;
82
+ this._executionTimes = this._executionTimes.filter(
97
83
  (time) => time > windowStart
98
84
  );
99
85
  }
86
+ /**
87
+ * Returns the number of times the function has been executed
88
+ */
89
+ getExecutionCount() {
90
+ return this._executionCount;
91
+ }
92
+ /**
93
+ * Returns the number of times the function has been rejected
94
+ */
95
+ getRejectionCount() {
96
+ return this._rejectionCount;
97
+ }
98
+ /**
99
+ * Returns the number of remaining executions allowed in the current window
100
+ */
101
+ getRemainingInWindow() {
102
+ this.cleanupOldExecutions();
103
+ return Math.max(0, this._options.limit - this._executionTimes.length);
104
+ }
105
+ /**
106
+ * Returns the number of milliseconds until the next execution will be possible
107
+ */
108
+ getMsUntilNextWindow() {
109
+ const oldestExecution = Math.min(...this._executionTimes);
110
+ return oldestExecution + this._options.window - Date.now();
111
+ }
100
112
  /**
101
113
  * Resets the rate limiter state
102
114
  */
103
115
  reset() {
104
- this.executionTimes = [];
105
- this.executionCount = 0;
106
- this.rejectionCount = 0;
116
+ this._executionTimes = [];
117
+ this._executionCount = 0;
118
+ this._rejectionCount = 0;
107
119
  }
108
120
  }
109
121
  function rateLimit(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.cjs","sources":["../../src/rate-limiter.ts"],"sourcesContent":["/**\n * Information about a rate limit rejection\n */\nexport interface RateLimitRejectionInfo {\n /**\n * Number of milliseconds until the next execution will be possible\n */\n msUntilNextWindow: number\n /**\n * Current number of executions in the window\n */\n currentExecutions: number\n /**\n * Maximum allowed executions per window\n */\n limit: number\n /**\n * Total number of rejections that have occurred\n */\n rejectionCount: number\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (info: RateLimitRejectionInfo) => void\n}\n\nconst defaultOptions: Required<Omit<RateLimiterOptions, 'onReject'>> = {\n enabled: true,\n limit: 1,\n window: 0,\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 * 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 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private rejectionCount = 0\n private executionTimes: Array<number> = []\n private options: RateLimiterOptions\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions,\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>): RateLimiterOptions {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\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.options.limit - this.executionTimes.length)\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: TArgs): boolean {\n this.cleanupOldExecutions()\n\n if (this.executionTimes.length < this.options.limit) {\n this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n\n return false\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n const now = Date.now()\n this.executionCount++\n this.executionTimes.push(now)\n this.fn(...args)\n }\n\n private rejectFunction(): void {\n this.rejectionCount++\n if (this.options.onReject) {\n const oldestExecution = Math.min(...this.executionTimes)\n const msUntilNextWindow =\n oldestExecution + this.options.window - Date.now()\n\n this.options.onReject({\n msUntilNextWindow,\n currentExecutions: this.executionTimes.length,\n limit: this.options.limit,\n rejectionCount: this.rejectionCount,\n })\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.options.window\n this.executionTimes = this.executionTimes.filter(\n (time) => time > windowStart,\n )\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 * 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\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: ({ msUntilNextWindow }) => {\n * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}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 (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":";;AA6CA,MAAM,iBAAiE;AAAA,EACrE,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AA2BO,MAAM,YAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,iBAAiB;AACzB,SAAQ,iBAAiB;AACzB,SAAQ,iBAAgC,CAAC;AAOvC,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAA6D;AACtE,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA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Ae;AAAA,MACxC,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAc;AACZ,SAAK,iBAAiB,CAAC;AACvB,SAAK,iBAAiB;AACtB,SAAK,iBAAiB;AAAA,EAAA;AAE1B;AAgCgB,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 type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn, TArgs>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn, TArgs>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any, any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\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 * 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 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn, TArgs>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn, TArgs>,\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(\n newOptions: Partial<RateLimiterOptions<TFn, TArgs>>,\n ): RateLimiterOptions<TFn, TArgs> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn, TArgs>> {\n return this._options as Required<RateLimiterOptions<TFn, TArgs>>\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: TArgs): boolean {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n\n return false\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this._options.enabled) 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._options.window\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._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this._options.window - 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 * 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\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\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: Omit<RateLimiterOptions<TFn, Parameters<TFn>>, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn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IAAI;AAAA,IAAA;AAAA,EAC7B;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,SAAS;AACnC,SAAA,kBAAkB,KAAK,gBAAgB;AAAA,MAC1C,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,SAAK,qBAAqB;AACnB,WAAA,KAAK,IAAI,GAAG,KAAK,SAAS,QAAQ,KAAK,gBAAgB,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMtE,uBAA+B;AAC7B,UAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,eAAe;AACxD,WAAO,kBAAkB,KAAK,SAAS,SAAS,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAgCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;;;"}
@@ -1,28 +1,8 @@
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
- }
1
+ import { AnyFunction } from './types.cjs';
22
2
  /**
23
3
  * Options for configuring a rate-limited function
24
4
  */
25
- export interface RateLimiterOptions {
5
+ export interface RateLimiterOptions<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
26
6
  /**
27
7
  * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
28
8
  * Defaults to true.
@@ -33,13 +13,17 @@ export interface RateLimiterOptions {
33
13
  */
34
14
  limit: number;
35
15
  /**
36
- * Time window in milliseconds within which the limit applies
16
+ * Callback function that is called after the function is executed
37
17
  */
38
- window: number;
18
+ onExecute?: (rateLimiter: RateLimiter<TFn, TArgs>) => void;
39
19
  /**
40
20
  * Optional callback function that is called when an execution is rejected due to rate limiting
41
21
  */
42
- onReject?: (info: RateLimitRejectionInfo) => void;
22
+ onReject?: (rateLimiter: RateLimiter<TFn, TArgs>) => void;
23
+ /**
24
+ * Time window in milliseconds within which the limit applies
25
+ */
26
+ window: number;
43
27
  }
44
28
  /**
45
29
  * A class that creates a rate-limited function.
@@ -66,30 +50,22 @@ export interface RateLimiterOptions {
66
50
  * rateLimiter.maybeExecute('123');
67
51
  * ```
68
52
  */
69
- export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
53
+ export declare class RateLimiter<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
70
54
  private fn;
71
- private executionCount;
72
- private rejectionCount;
73
- private executionTimes;
74
- private options;
75
- constructor(fn: TFn, initialOptions: RateLimiterOptions);
55
+ private _executionCount;
56
+ private _rejectionCount;
57
+ private _executionTimes;
58
+ private _options;
59
+ constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn, TArgs>);
76
60
  /**
77
61
  * Updates the rate limiter options
78
62
  * Returns the new options state
79
63
  */
80
- setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions;
81
- /**
82
- * Returns the number of times the function has been executed
83
- */
84
- getExecutionCount(): number;
64
+ setOptions(newOptions: Partial<RateLimiterOptions<TFn, TArgs>>): RateLimiterOptions<TFn, TArgs>;
85
65
  /**
86
- * Returns the number of times the function has been rejected
66
+ * Returns the current rate limiter options
87
67
  */
88
- getRejectionCount(): number;
89
- /**
90
- * Returns the number of remaining executions allowed in the current window
91
- */
92
- getRemainingInWindow(): number;
68
+ getOptions(): Required<RateLimiterOptions<TFn, TArgs>>;
93
69
  /**
94
70
  * Attempts to execute the rate-limited function if within the configured limits.
95
71
  * Will reject execution if the number of calls in the current window exceeds the limit.
@@ -109,6 +85,22 @@ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs
109
85
  private executeFunction;
110
86
  private rejectFunction;
111
87
  private cleanupOldExecutions;
88
+ /**
89
+ * Returns the number of times the function has been executed
90
+ */
91
+ getExecutionCount(): number;
92
+ /**
93
+ * Returns the number of times the function has been rejected
94
+ */
95
+ getRejectionCount(): number;
96
+ /**
97
+ * Returns the number of remaining executions allowed in the current window
98
+ */
99
+ getRemainingInWindow(): number;
100
+ /**
101
+ * Returns the number of milliseconds until the next execution will be possible
102
+ */
103
+ getMsUntilNextWindow(): number;
112
104
  /**
113
105
  * Resets the rate limiter state
114
106
  */
@@ -131,8 +123,8 @@ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs
131
123
  * const rateLimited = rateLimit(makeApiCall, {
132
124
  * limit: 5,
133
125
  * window: 60000,
134
- * onReject: ({ msUntilNextWindow }) => {
135
- * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
126
+ * onReject: (rateLimiter) => {
127
+ * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
136
128
  * }
137
129
  * });
138
130
  *
@@ -144,4 +136,4 @@ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs
144
136
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
145
137
  * ```
146
138
  */
147
- export declare function rateLimit<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<RateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => boolean;
139
+ export declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<RateLimiterOptions<TFn, Parameters<TFn>>, 'enabled'>): (...args: Parameters<TFn>) => boolean;
@@ -4,14 +4,17 @@ const defaultOptions = {
4
4
  enabled: true,
5
5
  leading: true,
6
6
  trailing: true,
7
- wait: 0
7
+ wait: 0,
8
+ onExecute: () => {
9
+ }
8
10
  };
9
11
  class Throttler {
10
12
  constructor(fn, initialOptions) {
11
13
  this.fn = fn;
12
- this.executionCount = 0;
13
- this.lastExecutionTime = 0;
14
- this.options = {
14
+ this._executionCount = 0;
15
+ this._lastExecutionTime = 0;
16
+ this._isPending = false;
17
+ this._options = {
15
18
  ...defaultOptions,
16
19
  ...initialOptions
17
20
  };
@@ -21,29 +24,17 @@ class Throttler {
21
24
  * Returns the new options state
22
25
  */
23
26
  setOptions(newOptions) {
24
- this.options = {
25
- ...this.options,
27
+ this._options = {
28
+ ...this._options,
26
29
  ...newOptions
27
30
  };
28
- return this.options;
29
- }
30
- /**
31
- * Returns the number of times the function has been executed
32
- */
33
- getExecutionCount() {
34
- return this.executionCount;
35
- }
36
- /**
37
- * Returns the last execution time
38
- */
39
- getLastExecutionTime() {
40
- return this.lastExecutionTime;
31
+ return this._options;
41
32
  }
42
33
  /**
43
- * Returns the next execution time
34
+ * Returns the current throttler options
44
35
  */
45
- getNextExecutionTime() {
46
- return this.lastExecutionTime + this.options.wait;
36
+ getOptions() {
37
+ return this._options;
47
38
  }
48
39
  /**
49
40
  * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
@@ -69,30 +60,34 @@ class Throttler {
69
60
  */
70
61
  maybeExecute(...args) {
71
62
  const now = Date.now();
72
- const timeSinceLastExecution = now - this.lastExecutionTime;
73
- if (timeSinceLastExecution >= this.options.wait) {
74
- if (this.options.leading) {
63
+ const timeSinceLastExecution = now - this._lastExecutionTime;
64
+ if (timeSinceLastExecution >= this._options.wait) {
65
+ if (this._options.leading) {
75
66
  this.executeFunction(...args);
76
67
  }
77
- this.lastExecutionTime = now;
68
+ this._lastExecutionTime = now;
69
+ this._isPending = false;
78
70
  } else {
79
- this.lastArgs = args;
80
- if (!this.timeoutId && this.options.trailing) {
81
- this.timeoutId = setTimeout(() => {
82
- if (this.lastArgs) {
83
- this.executeFunction(...this.lastArgs);
84
- this.lastArgs = void 0;
71
+ this._lastArgs = args;
72
+ if (!this._timeoutId && this._options.trailing) {
73
+ this._isPending = true;
74
+ this._timeoutId = setTimeout(() => {
75
+ if (this._lastArgs) {
76
+ this.executeFunction(...this._lastArgs);
77
+ this._lastArgs = void 0;
85
78
  }
86
- this.lastExecutionTime = Date.now();
87
- this.timeoutId = void 0;
88
- }, this.options.wait - timeSinceLastExecution);
79
+ this._lastExecutionTime = Date.now();
80
+ this._timeoutId = void 0;
81
+ this._isPending = false;
82
+ this._options.onExecute(this);
83
+ }, this._options.wait - timeSinceLastExecution);
89
84
  }
90
85
  }
91
86
  }
92
87
  executeFunction(...args) {
93
- if (!this.options.enabled) return;
94
- this.executionCount++;
88
+ if (!this._options.enabled) return;
95
89
  this.fn(...args);
90
+ this._executionCount++;
96
91
  }
97
92
  /**
98
93
  * Cancels any pending trailing execution and clears internal state.
@@ -104,12 +99,37 @@ class Throttler {
104
99
  * Has no effect if there is no pending execution.
105
100
  */
106
101
  cancel() {
107
- if (this.timeoutId) {
108
- clearTimeout(this.timeoutId);
109
- this.timeoutId = void 0;
110
- this.lastArgs = void 0;
102
+ if (this._timeoutId) {
103
+ clearTimeout(this._timeoutId);
104
+ this._timeoutId = void 0;
105
+ this._lastArgs = void 0;
106
+ this._isPending = false;
111
107
  }
112
108
  }
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
+ /**
122
+ * Returns the last execution time
123
+ */
124
+ getLastExecutionTime() {
125
+ return this._lastExecutionTime;
126
+ }
127
+ /**
128
+ * Returns the next execution time
129
+ */
130
+ getNextExecutionTime() {
131
+ return this._lastExecutionTime + this._options.wait;
132
+ }
113
133
  }
114
134
  function throttle(fn, initialOptions) {
115
135
  const throttler = new Throttler(fn, initialOptions);
@@ -1 +1 @@
1
- {"version":3,"file":"throttler.cjs","sources":["../../src/throttler.ts"],"sourcesContent":["/**\n * Options for configuring a throttled function\n */\nexport interface ThrottlerOptions {\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 * 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> = {\n enabled: true,\n leading: true,\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 rate limiting or hard API limits, consider using RateLimiter instead.\n * For collapsing rapid-fire events, 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<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private lastArgs: TArgs | undefined\n private lastExecutionTime = 0\n private options: Required<ThrottlerOptions>\n private timeoutId: NodeJS.Timeout | undefined\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions,\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(\n newOptions: Partial<ThrottlerOptions>,\n ): Required<ThrottlerOptions> {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\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 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 * 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: TArgs): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this.lastExecutionTime\n\n // Handle leading execution\n if (timeSinceLastExecution >= this.options.wait) {\n if (this.options.leading) {\n this.executeFunction(...args)\n }\n this.lastExecutionTime = now\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 this.timeoutId = setTimeout(() => {\n if (this.lastArgs) {\n this.executeFunction(...this.lastArgs)\n this.lastArgs = undefined\n }\n this.lastExecutionTime = Date.now()\n this.timeoutId = undefined\n }, this.options.wait - timeSinceLastExecution)\n }\n }\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n this.executionCount++\n this.fn(...args)\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/**\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 (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<ThrottlerOptions, 'enabled'>,\n) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":[],"mappings":";;AAyBA,MAAM,iBAA6C;AAAA,EACjD,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AA8BO,MAAM,UAGX;AAAA,EAOA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAPV,SAAQ,iBAAiB;AAEzB,SAAQ,oBAAoB;AAQ1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YAC4B;AAC5B,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;A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Ac;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
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<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n> {\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, TArgs>) => 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, any>> = {\n enabled: true,\n leading: true,\n trailing: true,\n wait: 0,\n onExecute: () => {},\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, TArgs extends Parameters<TFn>> {\n private _executionCount = 0\n private _lastArgs: TArgs | undefined\n private _lastExecutionTime = 0\n private _options: Required<ThrottlerOptions<TFn, TArgs>>\n private _timeoutId: NodeJS.Timeout | undefined\n private _isPending = false\n\n constructor(\n private fn: TFn,\n initialOptions: ThrottlerOptions<TFn, TArgs>,\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(\n newOptions: Partial<ThrottlerOptions<TFn, TArgs>>,\n ): Required<ThrottlerOptions<TFn, TArgs>> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current throttler options\n */\n getOptions(): Required<ThrottlerOptions<TFn, TArgs>> {\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: TArgs): void {\n const now = Date.now()\n const timeSinceLastExecution = now - this._lastExecutionTime\n\n // Handle leading execution\n if (timeSinceLastExecution >= this._options.wait) {\n if (this._options.leading) {\n this.executeFunction(...args)\n }\n this._lastExecutionTime = now\n this._isPending = false\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 this._isPending = true\n this._timeoutId = setTimeout(() => {\n if (this._lastArgs) {\n this.executeFunction(...this._lastArgs)\n this._lastArgs = undefined\n }\n this._lastExecutionTime = Date.now()\n this._timeoutId = undefined\n this._isPending = false\n this._options.onExecute(this)\n }, this._options.wait - timeSinceLastExecution)\n }\n }\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this._options.enabled) return\n this.fn(...args) // EXECUTE!\n this._executionCount++\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 this._isPending = false\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 `true` if there is a pending execution\n */\n getIsPending(): boolean {\n return this._options.enabled && this._isPending\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/**\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<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n>(fn: TFn, initialOptions: Omit<ThrottlerOptions<TFn, TArgs>, 'enabled'>) {\n const throttler = new Throttler(fn, initialOptions)\n return throttler.maybeExecute.bind(throttler)\n}\n"],"names":[],"mappings":";;AAkCA,MAAM,iBAAuD;AAAA,EAC3D,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AAAA,EACN,WAAW,MAAM;AAAA,EAAA;AACnB;AA6BO,MAAM,UAAkE;AAAA,EAQ7E,YACU,IACR,gBACA;AAFQ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GAAG,IAAI;AACV,SAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYP,SAAe;AACb,QAAI,KAAK,YAAY;AACnB,mBAAa,KAAK,UAAU;AAC5B,WAAK,aAAa;AAClB,WAAK,YAAY;AACjB,WAAK,aAAa;AAAA,IAAA;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAMF,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,SAAS,WAAW,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMvC,uBAA+B;AAC7B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AACtB,WAAA,KAAK,qBAAqB,KAAK,SAAS;AAAA,EAAA;AAEnD;AA4BgB,SAAA,SAGd,IAAS,gBAA+D;AACxE,QAAM,YAAY,IAAI,UAAU,IAAI,cAAc;AAC3C,SAAA,UAAU,aAAa,KAAK,SAAS;AAC9C;;;"}
@@ -1,7 +1,8 @@
1
+ import { AnyFunction } from './types.cjs';
1
2
  /**
2
3
  * Options for configuring a throttled function
3
4
  */
4
- export interface ThrottlerOptions {
5
+ export interface ThrottlerOptions<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
5
6
  /**
6
7
  * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
7
8
  * Defaults to true.
@@ -12,6 +13,10 @@ export interface ThrottlerOptions {
12
13
  * Defaults to true.
13
14
  */
14
15
  leading?: boolean;
16
+ /**
17
+ * Callback function that is called after the function is executed
18
+ */
19
+ onExecute?: (throttler: Throttler<TFn, TArgs>) => void;
15
20
  /**
16
21
  * Whether to execute on the trailing edge of the timeout.
17
22
  * Defaults to true.
@@ -33,8 +38,7 @@ export interface ThrottlerOptions {
33
38
  * - Leading: Execute immediately on first call (default: true)
34
39
  * - Trailing: Execute after wait period if called during throttle (default: true)
35
40
  *
36
- * For rate limiting or hard API limits, consider using RateLimiter instead.
37
- * For collapsing rapid-fire events, consider using Debouncer.
41
+ * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
38
42
  *
39
43
  * @example
40
44
  * ```ts
@@ -50,31 +54,24 @@ export interface ThrottlerOptions {
50
54
  * throttler.maybeExecute('123'); // Throttled
51
55
  * ```
52
56
  */
53
- export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
57
+ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
54
58
  private fn;
55
- private executionCount;
56
- private lastArgs;
57
- private lastExecutionTime;
58
- private options;
59
- private timeoutId;
60
- constructor(fn: TFn, initialOptions: ThrottlerOptions);
59
+ private _executionCount;
60
+ private _lastArgs;
61
+ private _lastExecutionTime;
62
+ private _options;
63
+ private _timeoutId;
64
+ private _isPending;
65
+ constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn, TArgs>);
61
66
  /**
62
67
  * Updates the throttler options
63
68
  * Returns the new options state
64
69
  */
65
- setOptions(newOptions: Partial<ThrottlerOptions>): Required<ThrottlerOptions>;
70
+ setOptions(newOptions: Partial<ThrottlerOptions<TFn, TArgs>>): Required<ThrottlerOptions<TFn, TArgs>>;
66
71
  /**
67
- * Returns the number of times the function has been executed
72
+ * Returns the current throttler options
68
73
  */
69
- getExecutionCount(): number;
70
- /**
71
- * Returns the last execution time
72
- */
73
- getLastExecutionTime(): number;
74
- /**
75
- * Returns the next execution time
76
- */
77
- getNextExecutionTime(): number;
74
+ getOptions(): Required<ThrottlerOptions<TFn, TArgs>>;
78
75
  /**
79
76
  * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
80
77
  *
@@ -109,6 +106,22 @@ export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs e
109
106
  * Has no effect if there is no pending execution.
110
107
  */
111
108
  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
+ /**
118
+ * Returns the last execution time
119
+ */
120
+ getLastExecutionTime(): number;
121
+ /**
122
+ * Returns the next execution time
123
+ */
124
+ getNextExecutionTime(): number;
112
125
  }
113
126
  /**
114
127
  * Creates a throttled function that limits how often the provided function can execute.
@@ -136,4 +149,4 @@ export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs e
136
149
  * });
137
150
  * ```
138
151
  */
139
- export declare function throttle<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<ThrottlerOptions, 'enabled'>): (...args: Parameters<TFn>) => void;
152
+ export declare function throttle<TFn extends AnyFunction, TArgs extends Parameters<TFn>>(fn: TFn, initialOptions: Omit<ThrottlerOptions<TFn, TArgs>, 'enabled'>): (...args: TArgs) => void;
@@ -0,0 +1,12 @@
1
+ /**
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
+ */
6
+ export type AnyFunction<TArgs extends Array<any> = Array<any>> = (...args: TArgs) => any;
7
+ /**
8
+ * 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
+ */
12
+ export type AnyAsyncFunction<TArgs extends Array<any> = Array<any>> = (...args: TArgs) => Promise<any>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ function bindInstanceMethods(instance) {
4
+ return Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).filter((key) => typeof instance[key] === "function").reduce((acc, key) => {
5
+ const method = instance[key];
6
+ if (typeof method === "function") {
7
+ acc[key] = method.bind(instance);
8
+ }
9
+ return acc;
10
+ }, {});
11
+ }
12
+ exports.bindInstanceMethods = bindInstanceMethods;
13
+ //# sourceMappingURL=utils.cjs.map