@tanstack/pacer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/async-debouncer.cjs +109 -0
  3. package/dist/cjs/async-debouncer.cjs.map +1 -0
  4. package/dist/cjs/async-debouncer.d.cts +99 -0
  5. package/dist/cjs/async-queuer.cjs +293 -0
  6. package/dist/cjs/async-queuer.cjs.map +1 -0
  7. package/dist/cjs/async-queuer.d.cts +197 -0
  8. package/dist/cjs/async-rate-limiter.cjs +122 -0
  9. package/dist/cjs/async-rate-limiter.cjs.map +1 -0
  10. package/dist/cjs/async-rate-limiter.d.cts +132 -0
  11. package/dist/cjs/async-throttler.cjs +115 -0
  12. package/dist/cjs/async-throttler.cjs.map +1 -0
  13. package/dist/cjs/async-throttler.d.cts +93 -0
  14. package/dist/cjs/compare.cjs +72 -0
  15. package/dist/cjs/compare.cjs.map +1 -0
  16. package/dist/cjs/compare.d.cts +12 -0
  17. package/dist/cjs/debouncer.cjs +74 -0
  18. package/dist/cjs/debouncer.cjs.map +1 -0
  19. package/dist/cjs/debouncer.d.cts +96 -0
  20. package/dist/cjs/index.cjs +32 -0
  21. package/dist/cjs/index.cjs.map +1 -0
  22. package/dist/cjs/index.d.cts +9 -0
  23. package/dist/cjs/queuer.cjs +231 -0
  24. package/dist/cjs/queuer.cjs.map +1 -0
  25. package/dist/cjs/queuer.d.cts +221 -0
  26. package/dist/cjs/rate-limiter.cjs +115 -0
  27. package/dist/cjs/rate-limiter.cjs.map +1 -0
  28. package/dist/cjs/rate-limiter.d.cts +147 -0
  29. package/dist/cjs/throttler.cjs +120 -0
  30. package/dist/cjs/throttler.cjs.map +1 -0
  31. package/dist/cjs/throttler.d.cts +139 -0
  32. package/dist/esm/async-debouncer.d.ts +99 -0
  33. package/dist/esm/async-debouncer.js +109 -0
  34. package/dist/esm/async-debouncer.js.map +1 -0
  35. package/dist/esm/async-queuer.d.ts +197 -0
  36. package/dist/esm/async-queuer.js +293 -0
  37. package/dist/esm/async-queuer.js.map +1 -0
  38. package/dist/esm/async-rate-limiter.d.ts +132 -0
  39. package/dist/esm/async-rate-limiter.js +122 -0
  40. package/dist/esm/async-rate-limiter.js.map +1 -0
  41. package/dist/esm/async-throttler.d.ts +93 -0
  42. package/dist/esm/async-throttler.js +115 -0
  43. package/dist/esm/async-throttler.js.map +1 -0
  44. package/dist/esm/compare.d.ts +12 -0
  45. package/dist/esm/compare.js +72 -0
  46. package/dist/esm/compare.js.map +1 -0
  47. package/dist/esm/debouncer.d.ts +96 -0
  48. package/dist/esm/debouncer.js +74 -0
  49. package/dist/esm/debouncer.js.map +1 -0
  50. package/dist/esm/index.d.ts +9 -0
  51. package/dist/esm/index.js +32 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/queuer.d.ts +221 -0
  54. package/dist/esm/queuer.js +231 -0
  55. package/dist/esm/queuer.js.map +1 -0
  56. package/dist/esm/rate-limiter.d.ts +147 -0
  57. package/dist/esm/rate-limiter.js +115 -0
  58. package/dist/esm/rate-limiter.js.map +1 -0
  59. package/dist/esm/throttler.d.ts +139 -0
  60. package/dist/esm/throttler.js +120 -0
  61. package/dist/esm/throttler.js.map +1 -0
  62. package/package.json +150 -0
  63. package/src/async-debouncer.ts +197 -0
  64. package/src/async-queuer.ts +447 -0
  65. package/src/async-rate-limiter.ts +228 -0
  66. package/src/async-throttler.ts +194 -0
  67. package/src/compare.ts +105 -0
  68. package/src/debouncer.ts +164 -0
  69. package/src/index.ts +9 -0
  70. package/src/queuer.ts +394 -0
  71. package/src/rate-limiter.ts +236 -0
  72. package/src/throttler.ts +222 -0
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Options for configuring a throttled function
3
+ */
4
+ export interface ThrottlerOptions {
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
+ * Whether to execute on the leading edge of the timeout.
12
+ * Defaults to true.
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
+ * Time window in milliseconds during which the function can only be executed once
22
+ */
23
+ wait: number
24
+ }
25
+
26
+ const defaultOptions: Required<ThrottlerOptions> = {
27
+ enabled: true,
28
+ leading: true,
29
+ trailing: true,
30
+ wait: 0,
31
+ }
32
+
33
+ /**
34
+ * A class that creates a throttled function.
35
+ *
36
+ * Throttling ensures a function is called at most once within a specified time window.
37
+ * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
38
+ * execution timing regardless of call frequency.
39
+ *
40
+ * Supports both leading and trailing edge execution:
41
+ * - Leading: Execute immediately on first call (default: true)
42
+ * - Trailing: Execute after wait period if called during throttle (default: true)
43
+ *
44
+ * For rate limiting or hard API limits, consider using RateLimiter instead.
45
+ * For collapsing rapid-fire events, consider using Debouncer.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const throttler = new Throttler(
50
+ * (id: string) => api.getData(id),
51
+ * { wait: 1000 } // Execute at most once per second
52
+ * );
53
+ *
54
+ * // First call executes immediately
55
+ * throttler.maybeExecute('123');
56
+ *
57
+ * // Subsequent calls within 1000ms are throttled
58
+ * throttler.maybeExecute('123'); // Throttled
59
+ * ```
60
+ */
61
+ export class Throttler<
62
+ TFn extends (...args: Array<any>) => any,
63
+ TArgs extends Parameters<TFn>,
64
+ > {
65
+ private executionCount = 0
66
+ private lastArgs: TArgs | undefined
67
+ private lastExecutionTime = 0
68
+ private options: Required<ThrottlerOptions>
69
+ private timeoutId: NodeJS.Timeout | undefined
70
+
71
+ constructor(
72
+ private fn: TFn,
73
+ initialOptions: ThrottlerOptions,
74
+ ) {
75
+ this.options = {
76
+ ...defaultOptions,
77
+ ...initialOptions,
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Updates the throttler options
83
+ * Returns the new options state
84
+ */
85
+ setOptions(
86
+ newOptions: Partial<ThrottlerOptions>,
87
+ ): Required<ThrottlerOptions> {
88
+ this.options = {
89
+ ...this.options,
90
+ ...newOptions,
91
+ }
92
+ return this.options
93
+ }
94
+
95
+ /**
96
+ * Returns the number of times the function has been executed
97
+ */
98
+ getExecutionCount(): number {
99
+ return this.executionCount
100
+ }
101
+
102
+ /**
103
+ * Returns the last execution time
104
+ */
105
+ getLastExecutionTime(): number {
106
+ return this.lastExecutionTime
107
+ }
108
+
109
+ /**
110
+ * Returns the next execution time
111
+ */
112
+ getNextExecutionTime(): number {
113
+ return this.lastExecutionTime + this.options.wait
114
+ }
115
+
116
+ /**
117
+ * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
118
+ *
119
+ * - If enough time has passed since the last execution (>= wait period):
120
+ * - With leading=true: Executes immediately
121
+ * - With leading=false: Waits for the next trailing execution
122
+ *
123
+ * - If within the wait period:
124
+ * - With trailing=true: Schedules execution for end of wait period
125
+ * - With trailing=false: Drops the execution
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * const throttled = new Throttler(fn, { wait: 1000 });
130
+ *
131
+ * // First call executes immediately
132
+ * throttled.maybeExecute('a', 'b');
133
+ *
134
+ * // Call during wait period - gets throttled
135
+ * throttled.maybeExecute('c', 'd');
136
+ * ```
137
+ */
138
+ maybeExecute(...args: TArgs): void {
139
+ const now = Date.now()
140
+ const timeSinceLastExecution = now - this.lastExecutionTime
141
+
142
+ // Handle leading execution
143
+ if (timeSinceLastExecution >= this.options.wait) {
144
+ if (this.options.leading) {
145
+ this.executeFunction(...args)
146
+ }
147
+ this.lastExecutionTime = now
148
+ } else {
149
+ // Store the most recent arguments for potential trailing execution
150
+ this.lastArgs = args
151
+
152
+ // Set up trailing execution if not already scheduled
153
+ if (!this.timeoutId && this.options.trailing) {
154
+ this.timeoutId = setTimeout(() => {
155
+ if (this.lastArgs) {
156
+ this.executeFunction(...this.lastArgs)
157
+ this.lastArgs = undefined
158
+ }
159
+ this.lastExecutionTime = Date.now()
160
+ this.timeoutId = undefined
161
+ }, this.options.wait - timeSinceLastExecution)
162
+ }
163
+ }
164
+ }
165
+
166
+ private executeFunction(...args: TArgs): void {
167
+ if (!this.options.enabled) return
168
+ this.executionCount++
169
+ this.fn(...args)
170
+ }
171
+
172
+ /**
173
+ * Cancels any pending trailing execution and clears internal state.
174
+ *
175
+ * If a trailing execution is scheduled (due to throttling with trailing=true),
176
+ * this will prevent that execution from occurring. The internal timeout and
177
+ * stored arguments will be cleared.
178
+ *
179
+ * Has no effect if there is no pending execution.
180
+ */
181
+ cancel(): void {
182
+ if (this.timeoutId) {
183
+ clearTimeout(this.timeoutId)
184
+ this.timeoutId = undefined
185
+ this.lastArgs = undefined
186
+ }
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Creates a throttled function that limits how often the provided function can execute.
192
+ *
193
+ * Throttling ensures a function executes at most once within a specified time window,
194
+ * regardless of how many times it is called. This is useful for rate-limiting
195
+ * expensive operations or UI updates.
196
+ *
197
+ * The throttled function can be configured to execute on the leading and/or trailing
198
+ * edge of the throttle window via options.
199
+ *
200
+ * For handling bursts of events, consider using debounce() instead. For hard execution
201
+ * limits, consider using rateLimit().
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * // Basic throttling - max once per second
206
+ * const throttled = throttle(updateUI, { wait: 1000 });
207
+ *
208
+ * // Configure leading/trailing execution
209
+ * const throttled = throttle(saveData, {
210
+ * wait: 2000,
211
+ * leading: true, // Execute immediately on first call
212
+ * trailing: true // Execute again after delay if called during wait
213
+ * });
214
+ * ```
215
+ */
216
+ export function throttle<TFn extends (...args: Array<any>) => any>(
217
+ fn: TFn,
218
+ initialOptions: Omit<ThrottlerOptions, 'enabled'>,
219
+ ) {
220
+ const throttler = new Throttler(fn, initialOptions)
221
+ return throttler.maybeExecute.bind(throttler)
222
+ }