@avatijs/debounce 0.1.1 → 0.1.3
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +135 -217
- package/dist/cjs/index.js +368 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/index.min.js +7 -0
- package/dist/cjs/index.min.js.map +1 -0
- package/dist/esm/index.js +353 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.min.js +7 -0
- package/dist/esm/index.min.js.map +1 -0
- package/dist/types/debouce.d.ts +1 -0
- package/dist/types/debouce.d.ts.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/umd/index.js +378 -2
- package/dist/umd/index.js.map +1 -1
- package/dist/umd/index.min.js +8 -0
- package/dist/umd/index.min.js.map +1 -0
- package/package.json +12 -5
- package/dist/debouce.d.ts +0 -72
- package/dist/index.d.ts +0 -1
package/dist/esm/index.js
CHANGED
@@ -1,7 +1,358 @@
|
|
1
1
|
/*!
|
2
|
-
* @avatijs/debounce 0.1.
|
2
|
+
* @avatijs/debounce 0.1.3
|
3
3
|
* Copyright (c) 2024 Khaled Sameer <khaled.smq@hotmail.com>
|
4
4
|
* Licensed under MIT, https://opensource.org/licenses/MIT/
|
5
5
|
* Please visit https://avati.io/ for details.
|
6
|
-
*/
|
6
|
+
*/
|
7
|
+
|
8
|
+
/* eslint-disable */
|
9
|
+
|
10
|
+
/******/ // The require scope
|
11
|
+
/******/ var __webpack_require__ = {};
|
12
|
+
/******/
|
13
|
+
/************************************************************************/
|
14
|
+
/******/ /* webpack/runtime/define property getters */
|
15
|
+
/******/ (() => {
|
16
|
+
/******/ // define getter functions for harmony exports
|
17
|
+
/******/ __webpack_require__.d = (exports, definition) => {
|
18
|
+
/******/ for(var key in definition) {
|
19
|
+
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
|
20
|
+
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
|
21
|
+
/******/ }
|
22
|
+
/******/ }
|
23
|
+
/******/ };
|
24
|
+
/******/ })();
|
25
|
+
/******/
|
26
|
+
/******/ /* webpack/runtime/hasOwnProperty shorthand */
|
27
|
+
/******/ (() => {
|
28
|
+
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
|
29
|
+
/******/ })();
|
30
|
+
/******/
|
31
|
+
/************************************************************************/
|
32
|
+
var __webpack_exports__ = {};
|
33
|
+
|
34
|
+
// EXPORTS
|
35
|
+
__webpack_require__.d(__webpack_exports__, {
|
36
|
+
s: () => (/* reexport */ debounce)
|
37
|
+
});
|
38
|
+
|
39
|
+
;// ./src/debouce.ts
|
40
|
+
/**
|
41
|
+
* Advanced debounce utility with TypeScript support
|
42
|
+
* Provides a way to limit the rate at which a function can fire by delaying its execution
|
43
|
+
* until after a specified amount of time has elapsed since its last invocation.
|
44
|
+
* @module debounce
|
45
|
+
*/
|
46
|
+
/** WeakMap to store private state for each debounced function */
|
47
|
+
const privateState = new WeakMap();
|
48
|
+
/**
|
49
|
+
* Creates a logger instance based on debug flag
|
50
|
+
* @param debug - Whether debug logging is enabled
|
51
|
+
* @returns Object with logging methods
|
52
|
+
* @private
|
53
|
+
*/
|
54
|
+
const createLogger = (debug) => ({
|
55
|
+
log: (...args) => debug && console.log('[Debounce]', ...args),
|
56
|
+
warn: (...args) => debug && console.warn('[Debounce]', ...args),
|
57
|
+
error: (...args) => debug && console.error('[Debounce]', ...args),
|
58
|
+
});
|
59
|
+
/**
|
60
|
+
* Creates a debounced version of the provided function that delays invoking func until after
|
61
|
+
* wait milliseconds have elapsed since the last time the debounced function was invoked.
|
62
|
+
*
|
63
|
+
* @template T - The type of the function to debounce
|
64
|
+
* @param {T} func - The function to debounce
|
65
|
+
* @param {DebounceOptions} [options={}] - Configuration options
|
66
|
+
* @returns {DebouncedFunction<T>} The debounced function
|
67
|
+
* @throws {TypeError} If func is not a function
|
68
|
+
* @throws {RangeError} If wait or maxWait values are invalid
|
69
|
+
* @throws {Error} If neither leading nor trailing is true
|
70
|
+
*
|
71
|
+
* @example
|
72
|
+
* const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });
|
73
|
+
* await debouncedFn(5); // Will execute after 1000ms of inactivity
|
74
|
+
* const debouncedFn = debounce(
|
75
|
+
* async (x: number) => x * 2,
|
76
|
+
* {
|
77
|
+
* wait: 1000,
|
78
|
+
* onError: (error) => console.error('Error in debounced function:', error)
|
79
|
+
* }
|
80
|
+
* );
|
81
|
+
*/
|
82
|
+
function debounce(func, options = {}) {
|
83
|
+
// Input validation
|
84
|
+
if (typeof func !== 'function') {
|
85
|
+
throw new TypeError('Expected a function');
|
86
|
+
}
|
87
|
+
const { wait = 0, leading = false, trailing = true, maxWait, debug = false, signal, onError, } = options;
|
88
|
+
// Validate options
|
89
|
+
if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {
|
90
|
+
throw new RangeError('Invalid wait/maxWait values');
|
91
|
+
}
|
92
|
+
if (!leading && !trailing) {
|
93
|
+
throw new Error('At least one of leading or trailing must be true');
|
94
|
+
}
|
95
|
+
const logger = createLogger(debug);
|
96
|
+
const state = {
|
97
|
+
lastInvokeTime: 0,
|
98
|
+
pendingPromises: [],
|
99
|
+
aborted: false,
|
100
|
+
};
|
101
|
+
// Setup abort controller handling
|
102
|
+
if (signal) {
|
103
|
+
signal.addEventListener('abort', () => {
|
104
|
+
state.aborted = true;
|
105
|
+
cancel();
|
106
|
+
});
|
107
|
+
}
|
108
|
+
/**
|
109
|
+
* Cancels all active timers
|
110
|
+
* @private
|
111
|
+
*/
|
112
|
+
function cancelTimers() {
|
113
|
+
if (state.timerId !== undefined) {
|
114
|
+
clearTimeout(state.timerId);
|
115
|
+
state.timerId = undefined;
|
116
|
+
logger.log('Cleared debounce timer');
|
117
|
+
}
|
118
|
+
if (state.maxTimerId !== undefined) {
|
119
|
+
clearTimeout(state.maxTimerId);
|
120
|
+
state.maxTimerId = undefined;
|
121
|
+
logger.log('Cleared max wait timer');
|
122
|
+
}
|
123
|
+
}
|
124
|
+
/**
|
125
|
+
* Cancels any pending function invocations
|
126
|
+
* Rejects all pending promises and resets internal state
|
127
|
+
*/
|
128
|
+
function cancel() {
|
129
|
+
logger.log('Cancelling pending invocations');
|
130
|
+
cancelTimers();
|
131
|
+
state.lastInvokeTime = 0;
|
132
|
+
state.lastArgs = undefined;
|
133
|
+
state.lastThis = undefined;
|
134
|
+
state.lastCallTime = undefined;
|
135
|
+
const error = new Error('Debounced function cancelled');
|
136
|
+
handleError(error);
|
137
|
+
state.pendingPromises.forEach(({ reject }) => reject(new Error('Debounced function cancelled')));
|
138
|
+
state.pendingPromises = [];
|
139
|
+
}
|
140
|
+
/**
|
141
|
+
* Handles errors during function execution
|
142
|
+
* @param {Error} error - The error that occurred
|
143
|
+
* @private
|
144
|
+
*/
|
145
|
+
function handleError(error) {
|
146
|
+
logger.error('Error occurred:', error);
|
147
|
+
if (onError) {
|
148
|
+
try {
|
149
|
+
onError(error);
|
150
|
+
}
|
151
|
+
catch (callbackError) {
|
152
|
+
logger.error('Error in onError callback:', callbackError);
|
153
|
+
}
|
154
|
+
}
|
155
|
+
}
|
156
|
+
/**
|
157
|
+
* Checks if there are any pending function invocations
|
158
|
+
* @returns {boolean} True if there are pending invocations
|
159
|
+
*/
|
160
|
+
function pending() {
|
161
|
+
return state.timerId !== undefined;
|
162
|
+
}
|
163
|
+
/**
|
164
|
+
* Determines if the function should be invoked based on timing conditions
|
165
|
+
* @param {number} time - Current timestamp
|
166
|
+
* @returns {boolean} True if function should be invoked
|
167
|
+
* @private
|
168
|
+
*/
|
169
|
+
function shouldInvoke(time) {
|
170
|
+
if (state.aborted)
|
171
|
+
return false;
|
172
|
+
const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;
|
173
|
+
const timeSinceLastInvoke = time - state.lastInvokeTime;
|
174
|
+
return (state.lastCallTime === undefined ||
|
175
|
+
timeSinceLastCall >= wait ||
|
176
|
+
timeSinceLastCall < 0 ||
|
177
|
+
(maxWait !== undefined && timeSinceLastInvoke >= maxWait));
|
178
|
+
}
|
179
|
+
/**
|
180
|
+
* Executes the underlying function and manages promise resolution
|
181
|
+
* @param {number} time - Current timestamp
|
182
|
+
* @returns {Promise} Promise resolving to function result
|
183
|
+
* @private
|
184
|
+
*/
|
185
|
+
async function invokeFunc(time) {
|
186
|
+
logger.log(`Invoking function at ${time}`);
|
187
|
+
state.lastInvokeTime = time;
|
188
|
+
const args = state.lastArgs;
|
189
|
+
const thisArg = state.lastThis;
|
190
|
+
state.lastArgs = undefined;
|
191
|
+
state.lastThis = undefined;
|
192
|
+
try {
|
193
|
+
const result = await func.apply(thisArg, args);
|
194
|
+
state.result = result;
|
195
|
+
state.pendingPromises.forEach(({ resolve }) => resolve(result));
|
196
|
+
state.pendingPromises = [];
|
197
|
+
logger.log('Function invoked successfully', result);
|
198
|
+
return result;
|
199
|
+
}
|
200
|
+
catch (error) {
|
201
|
+
const wrappedError = error instanceof Error ? error : new Error(String(error));
|
202
|
+
logger.error('Error in function invocation:', wrappedError);
|
203
|
+
handleError(wrappedError);
|
204
|
+
// Clear pending promises after handling error
|
205
|
+
const currentPromises = [...state.pendingPromises];
|
206
|
+
state.pendingPromises = [];
|
207
|
+
// Reject all pending promises
|
208
|
+
currentPromises.forEach(({ reject }) => reject(wrappedError));
|
209
|
+
}
|
210
|
+
}
|
211
|
+
/**
|
212
|
+
* Starts both the debounce timer and maxWait timer if configured
|
213
|
+
* @param {number} time - Current timestamp
|
214
|
+
* @private
|
215
|
+
*/
|
216
|
+
function startTimer(time) {
|
217
|
+
const remainingTime = remainingWait(time);
|
218
|
+
state.timerId = setTimeout(timerExpired, remainingTime);
|
219
|
+
logger.log(`Started debounce timer for ${remainingTime}ms`);
|
220
|
+
if (maxWait !== undefined && !state.maxTimerId) {
|
221
|
+
const timeToMaxWait = maxWait - (time - state.lastCallTime);
|
222
|
+
state.maxTimerId = setTimeout(() => {
|
223
|
+
logger.log('Max wait timer expired');
|
224
|
+
cancelTimers();
|
225
|
+
invokeFunc(Date.now());
|
226
|
+
}, Math.max(0, timeToMaxWait));
|
227
|
+
logger.log(`Started max wait timer for ${timeToMaxWait}ms`);
|
228
|
+
}
|
229
|
+
}
|
230
|
+
/**
|
231
|
+
* Calculates remaining wait time before next execution
|
232
|
+
* @param {number} time - Current timestamp
|
233
|
+
* @returns {number} Milliseconds until next allowed execution
|
234
|
+
* @private
|
235
|
+
*/
|
236
|
+
function remainingWait(time) {
|
237
|
+
const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;
|
238
|
+
return Math.max(0, wait - timeSinceLastCall);
|
239
|
+
}
|
240
|
+
/**
|
241
|
+
* Handles timer expiration
|
242
|
+
* @private
|
243
|
+
*/
|
244
|
+
function timerExpired() {
|
245
|
+
const time = Date.now();
|
246
|
+
logger.log('Debounce timer expired');
|
247
|
+
if (shouldInvoke(time)) {
|
248
|
+
return trailingEdge(time);
|
249
|
+
}
|
250
|
+
startTimer(time);
|
251
|
+
}
|
252
|
+
/**
|
253
|
+
* Handles leading edge execution
|
254
|
+
* @param {number} time - Current timestamp
|
255
|
+
* @private
|
256
|
+
*/
|
257
|
+
function leadingEdge(time) {
|
258
|
+
logger.log('Leading edge triggered');
|
259
|
+
state.lastInvokeTime = time;
|
260
|
+
startTimer(time);
|
261
|
+
if (leading) {
|
262
|
+
invokeFunc(time);
|
263
|
+
}
|
264
|
+
}
|
265
|
+
/**
|
266
|
+
* Handles trailing edge execution
|
267
|
+
* @param {number} time - Current timestamp
|
268
|
+
* @private
|
269
|
+
*/
|
270
|
+
function trailingEdge(time) {
|
271
|
+
logger.log('Trailing edge triggered');
|
272
|
+
cancelTimers();
|
273
|
+
if (trailing && state.lastArgs) {
|
274
|
+
invokeFunc(time);
|
275
|
+
}
|
276
|
+
else {
|
277
|
+
state.pendingPromises.forEach(({ resolve }) => {
|
278
|
+
resolve(state.result);
|
279
|
+
});
|
280
|
+
state.pendingPromises = [];
|
281
|
+
}
|
282
|
+
}
|
283
|
+
/**
|
284
|
+
* Immediately executes the debounced function
|
285
|
+
* @param {...Parameters<T>} args - Function arguments
|
286
|
+
* @returns {Promise<ReturnType<T>>} Promise resolving to function result
|
287
|
+
*/
|
288
|
+
async function flush(...args) {
|
289
|
+
logger.log('Flush requested');
|
290
|
+
const argsToUse = args.length > 0 ? args : state.lastArgs;
|
291
|
+
const thisArg = state.lastThis;
|
292
|
+
cancelTimers();
|
293
|
+
if (argsToUse) {
|
294
|
+
state.lastArgs = argsToUse;
|
295
|
+
state.lastThis = thisArg;
|
296
|
+
return invokeFunc(Date.now());
|
297
|
+
}
|
298
|
+
return Promise.resolve(state.result);
|
299
|
+
}
|
300
|
+
/**
|
301
|
+
* Cleans up resources used by the debounced function
|
302
|
+
*/
|
303
|
+
function cleanup() {
|
304
|
+
logger.log('Cleanup initiated');
|
305
|
+
cancel();
|
306
|
+
privateState.delete(debounced);
|
307
|
+
}
|
308
|
+
/**
|
309
|
+
* The debounced function that wraps the original
|
310
|
+
* @param {...Parameters<T>} args - Function arguments
|
311
|
+
* @returns {Promise<ReturnType<T>>} Promise resolving to function result
|
312
|
+
*/
|
313
|
+
const debounced = function (...args) {
|
314
|
+
if (state.aborted) {
|
315
|
+
return Promise.reject(new Error('Debounced function aborted'));
|
316
|
+
}
|
317
|
+
const time = Date.now();
|
318
|
+
const isInvoking = shouldInvoke(time);
|
319
|
+
state.lastArgs = args;
|
320
|
+
state.lastThis = this;
|
321
|
+
state.lastCallTime = time;
|
322
|
+
logger.log('Function called', {
|
323
|
+
time,
|
324
|
+
isInvoking,
|
325
|
+
args,
|
326
|
+
pending: pending(),
|
327
|
+
});
|
328
|
+
return new Promise((resolve, reject) => {
|
329
|
+
state.pendingPromises.push({ resolve, reject });
|
330
|
+
if (state.timerId === undefined) {
|
331
|
+
leadingEdge(time);
|
332
|
+
}
|
333
|
+
else {
|
334
|
+
cancelTimers();
|
335
|
+
startTimer(time);
|
336
|
+
}
|
337
|
+
});
|
338
|
+
};
|
339
|
+
// Store private state
|
340
|
+
privateState.set(debounced, state);
|
341
|
+
// Add utility methods
|
342
|
+
Object.defineProperties(debounced, {
|
343
|
+
cancel: { value: cancel, writable: false, configurable: false },
|
344
|
+
flush: { value: flush, writable: false, configurable: false },
|
345
|
+
pending: { value: pending, writable: false, configurable: false },
|
346
|
+
cleanup: { value: cleanup, writable: false, configurable: false },
|
347
|
+
});
|
348
|
+
return debounced;
|
349
|
+
}
|
350
|
+
|
351
|
+
|
352
|
+
;// ./src/index.ts
|
353
|
+
|
354
|
+
|
355
|
+
var __webpack_exports__debounce = __webpack_exports__.s;
|
356
|
+
export { __webpack_exports__debounce as debounce };
|
357
|
+
|
7
358
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","mappings":";;;;;GACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,I,sBC0FlF,MAAMI,EAAe,IAAIC,QAQnBC,EAAgBC,IAAmB,CACrCC,IAAK,IAAIC,IAAgBF,QAASG,EAClCC,KAAM,IAAIF,IAAgBF,QAASG,EACnCE,MAAO,IAAIH,IAAgBF,QAASG,IA0BxC,SAASG,EACLC,EACAC,EAA2B,CAAC,GAG5B,GAAoB,mBAATD,EACP,MAAM,IAAIE,UAAU,uBAGxB,MAAM,KACFC,EAAO,EAAC,QACRC,GAAU,EAAK,SACfC,GAAW,EAAI,QACfC,EAAO,MACPb,GAAQ,EAAK,OACbc,EAAM,QACNC,GACAP,EAGJ,GAAW,EAAPE,QAAyBM,IAAZH,GAAmCH,EAAVG,EACtC,MAAM,IAAII,WAAW,+BAGz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ack/bootstrap","webpack://@avatijs/debounce/webpack/runtime/define property getters","webpack://@avatijs/debounce/webpack/runtime/hasOwnProperty shorthand","webpack://@avatijs/debounce/./src/debouce.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/**\n * Advanced debounce utility with TypeScript support\n * Provides a way to limit the rate at which a function can fire by delaying its execution\n * until after a specified amount of time has elapsed since its last invocation.\n * @module debounce\n */\n\n/**\n * Timer ID type returned by setTimeout\n * Used for managing timers internally\n */\ntype TimerId = ReturnType<typeof setTimeout>;\n\n/**\n * Generic function type that can accept any arguments and return any value\n * Used as a constraint for functions that can be debounced\n */\ntype AnyFunction = (...args: any[]) => any;\n\n/**\n * Configuration options for the debounce function\n * @interface DebounceOptions\n */\ninterface DebounceOptions {\n /** Number of milliseconds to delay execution (default: 0) */\n readonly wait?: number;\n /** Whether to execute on the leading edge of the timeout (default: false) */\n readonly leading?: boolean;\n /** Whether to execute on the trailing edge of the timeout (default: true) */\n readonly trailing?: boolean;\n /** Maximum time the function can be delayed before forced execution */\n readonly maxWait?: number;\n /** Enable debug logging for troubleshooting */\n readonly debug?: boolean;\n /** AbortController signal for cancellation */\n readonly signal?: AbortSignal;\n\n onError?: (error: Error) => void;\n}\n\n/**\n * Interface for the debounced function, including utility methods\n * @interface DebouncedFunction\n * @template T - The type of the original function\n */\ninterface DebouncedFunction<T extends AnyFunction> {\n /** Cancels any pending function invocations */\n readonly cancel: () => void;\n /** Immediately executes any pending function call */\n readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n /** Checks if there are any pending invocations */\n readonly pending: () => boolean;\n /** Cleans up resources used by the debounced function */\n readonly cleanup: () => void;\n\n /** The debounced function that wraps the original */\n (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n/**\n * Internal state management for the debounced function\n * @interface PrivateState\n * @template T - The type of the original function\n * @private\n */\ninterface PrivateState<T extends AnyFunction> {\n /** Current timer ID for the debounce delay */\n timerId?: TimerId;\n /** Timer ID for the maximum wait limit */\n maxTimerId?: TimerId;\n /** Timestamp of the last function call */\n lastCallTime?: number;\n /** Timestamp of the last successful function invocation */\n lastInvokeTime: number;\n /** Arguments from the most recent function call */\n lastArgs?: Parameters<T>;\n /** Execution context (this) from the most recent call */\n lastThis?: any;\n /** Result from the last function execution */\n result?: Awaited<ReturnType<T>>;\n /** Array of pending promises waiting for resolution */\n pendingPromises: Array<{\n resolve: (value: Awaited<ReturnType<T>>) => void;\n reject: (reason?: any) => void;\n }>;\n /** Flag indicating if the function has been aborted */\n aborted: boolean;\n}\n\n/** WeakMap to store private state for each debounced function */\nconst privateState = new WeakMap<DebouncedFunction<any>, PrivateState<any>>();\n\n/**\n * Creates a logger instance based on debug flag\n * @param debug - Whether debug logging is enabled\n * @returns Object with logging methods\n * @private\n */\nconst createLogger = (debug: boolean) => ({\n log: (...args: any[]) => debug && console.log('[Debounce]', ...args),\n warn: (...args: any[]) => debug && console.warn('[Debounce]', ...args),\n error: (...args: any[]) => debug && console.error('[Debounce]', ...args),\n});\n\n/**\n * Creates a debounced version of the provided function that delays invoking func until after\n * wait milliseconds have elapsed since the last time the debounced function was invoked.\n *\n * @template T - The type of the function to debounce\n * @param {T} func - The function to debounce\n * @param {DebounceOptions} [options={}] - Configuration options\n * @returns {DebouncedFunction<T>} The debounced function\n * @throws {TypeError} If func is not a function\n * @throws {RangeError} If wait or maxWait values are invalid\n * @throws {Error} If neither leading nor trailing is true\n *\n * @example\n * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });\n * await debouncedFn(5); // Will execute after 1000ms of inactivity\n * const debouncedFn = debounce(\n * async (x: number) => x * 2,\n * {\n * wait: 1000,\n * onError: (error) => console.error('Error in debounced function:', error)\n * }\n * );\n */\nfunction debounce<T extends AnyFunction>(\n func: T,\n options: DebounceOptions = {},\n): DebouncedFunction<T> {\n // Input validation\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n const {\n wait = 0,\n leading = false,\n trailing = true,\n maxWait,\n debug = false,\n signal,\n onError,\n } = options;\n\n // Validate options\n if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {\n throw new RangeError('Invalid wait/maxWait values');\n }\n\n if (!leading && !trailing) {\n throw new Error('At least one of leading or trailing must be true');\n }\n\n const logger = createLogger(debug);\n const state: PrivateState<T> = {\n lastInvokeTime: 0,\n pendingPromises: [],\n aborted: false,\n };\n\n // Setup abort controller handling\n if (signal) {\n signal.addEventListener('abort', () => {\n state.aborted = true;\n cancel();\n });\n }\n\n /**\n * Cancels all active timers\n * @private\n */\n function cancelTimers(): void {\n if (state.timerId !== undefined) {\n clearTimeout(state.timerId);\n state.timerId = undefined;\n logger.log('Cleared debounce timer');\n }\n if (state.maxTimerId !== undefined) {\n clearTimeout(state.maxTimerId);\n state.maxTimerId = undefined;\n logger.log('Cleared max wait timer');\n }\n }\n\n /**\n * Cancels any pending function invocations\n * Rejects all pending promises and resets internal state\n */\n function cancel(): void {\n logger.log('Cancelling pending invocations');\n cancelTimers();\n state.lastInvokeTime = 0;\n state.lastArgs = undefined;\n state.lastThis = undefined;\n state.lastCallTime = undefined;\n const error = new Error('Debounced function cancelled');\n handleError(error);\n state.pendingPromises.forEach(({ reject }) =>\n reject(new Error('Debounced function cancelled')),\n );\n state.pendingPromises = [];\n }\n\n /**\n * Handles errors during function execution\n * @param {Error} error - The error that occurred\n * @private\n */\n function handleError(error: Error): void {\n logger.error('Error occurred:', error);\n if (onError) {\n try {\n onError(error);\n } catch (callbackError) {\n logger.error('Error in onError callback:', callbackError);\n }\n }\n }\n\n /**\n * Checks if there are any pending function invocations\n * @returns {boolean} True if there are pending invocations\n */\n function pending(): boolean {\n return state.timerId !== undefined;\n }\n\n /**\n * Determines if the function should be invoked based on timing conditions\n * @param {number} time - Current timestamp\n * @returns {boolean} True if function should be invoked\n * @private\n */\n function shouldInvoke(time: number): boolean {\n if (state.aborted) return false;\n\n const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;\n const timeSinceLastInvoke = time - state.lastInvokeTime;\n\n return (\n state.lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxWait !== undefined && timeSinceLastInvoke >= maxWait)\n );\n }\n\n /**\n * Executes the underlying function and manages promise resolution\n * @param {number} time - Current timestamp\n * @returns {Promise} Promise resolving to function result\n * @private\n */\n async function invokeFunc(time: number): Promise<Awaited<ReturnType<T>> | void> {\n logger.log(`Invoking function at ${time}`);\n state.lastInvokeTime = time;\n const args = state.lastArgs!;\n const thisArg = state.lastThis;\n\n state.lastArgs = undefined;\n state.lastThis = undefined;\n\n try {\n const result = await func.apply(thisArg, args);\n state.result = result;\n state.pendingPromises.forEach(({ resolve }) => resolve(result));\n state.pendingPromises = [];\n logger.log('Function invoked successfully', result);\n return result;\n } catch (error) {\n const wrappedError = error instanceof Error ? error : new Error(String(error));\n logger.error('Error in function invocation:', wrappedError);\n handleError(wrappedError);\n\n // Clear pending promises after handling error\n const currentPromises = [...state.pendingPromises];\n state.pendingPromises = [];\n\n // Reject all pending promises\n currentPromises.forEach(({ reject }) => reject(wrappedError));\n }\n }\n\n /**\n * Starts both the debounce timer and maxWait timer if configured\n * @param {number} time - Current timestamp\n * @private\n */\n function startTimer(time: number): void {\n const remainingTime = remainingWait(time);\n state.timerId = setTimeout(timerExpired, remainingTime);\n logger.log(`Started debounce timer for ${remainingTime}ms`);\n\n if (maxWait !== undefined && !state.maxTimerId) {\n const timeToMaxWait = maxWait - (time - state.lastCallTime!);\n state.maxTimerId = setTimeout(\n () => {\n logger.log('Max wait timer expired');\n cancelTimers();\n invokeFunc(Date.now());\n },\n Math.max(0, timeToMaxWait),\n );\n logger.log(`Started max wait timer for ${timeToMaxWait}ms`);\n }\n }\n\n /**\n * Calculates remaining wait time before next execution\n * @param {number} time - Current timestamp\n * @returns {number} Milliseconds until next allowed execution\n * @private\n */\n function remainingWait(time: number): number {\n const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;\n return Math.max(0, wait - timeSinceLastCall);\n }\n\n /**\n * Handles timer expiration\n * @private\n */\n function timerExpired(): void {\n const time = Date.now();\n logger.log('Debounce timer expired');\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n\n startTimer(time);\n }\n\n /**\n * Handles leading edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function leadingEdge(time: number): void {\n logger.log('Leading edge triggered');\n state.lastInvokeTime = time;\n startTimer(time);\n\n if (leading) {\n invokeFunc(time);\n }\n }\n\n /**\n * Handles trailing edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function trailingEdge(time: number): void {\n logger.log('Trailing edge triggered');\n cancelTimers();\n\n if (trailing && state.lastArgs) {\n invokeFunc(time);\n } else {\n state.pendingPromises.forEach(({ resolve }) => {\n resolve(state.result as Awaited<ReturnType<T>>);\n });\n state.pendingPromises = [];\n }\n }\n\n /**\n * Immediately executes the debounced function\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n async function flush(...args: Parameters<T>): Promise<Awaited<ReturnType<T>> | void> {\n logger.log('Flush requested');\n const argsToUse = args.length > 0 ? args : state.lastArgs;\n const thisArg = state.lastThis;\n\n cancelTimers();\n\n if (argsToUse) {\n state.lastArgs = argsToUse;\n state.lastThis = thisArg;\n return invokeFunc(Date.now());\n }\n\n return Promise.resolve(state.result!);\n }\n\n /**\n * Cleans up resources used by the debounced function\n */\n function cleanup(): void {\n logger.log('Cleanup initiated');\n cancel();\n privateState.delete(debounced);\n }\n\n /**\n * The debounced function that wraps the original\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n const debounced = function(\n this: any,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n if (state.aborted) {\n return Promise.reject(new Error('Debounced function aborted'));\n }\n\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n state.lastArgs = args;\n state.lastThis = this;\n state.lastCallTime = time;\n\n logger.log('Function called', {\n time,\n isInvoking,\n args,\n pending: pending(),\n });\n\n return new Promise((resolve, reject) => {\n state.pendingPromises.push({ resolve, reject });\n\n if (state.timerId === undefined) {\n leadingEdge(time);\n } else {\n cancelTimers();\n startTimer(time);\n }\n });\n } as DebouncedFunction<T>;\n\n // Store private state\n privateState.set(debounced, state);\n\n // Add utility methods\n Object.defineProperties(debounced, {\n cancel: { value: cancel, writable: false, configurable: false },\n flush: { value: flush, writable: false, configurable: false },\n pending: { value: pending, writable: false, configurable: false },\n cleanup: { value: cleanup, writable: false, configurable: false },\n });\n\n return debounced;\n}\n\nexport { debounce, type DebouncedFunction, type DebounceOptions };\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","privateState","WeakMap","createLogger","debug","log","args","console","warn","error","debounce","func","options","TypeError","wait","leading","trailing","maxWait","signal","onError","undefined","RangeError","Error","logger","state","lastInvokeTime","pendingPromises","aborted","cancelTimers","timerId","clearTimeout","maxTimerId","cancel","lastArgs","lastThis","lastCallTime","handleError","forEach","reject","callbackError","pending","shouldInvoke","time","timeSinceLastCall","async","invokeFunc","thisArg","result","apply","resolve","wrappedError","String","currentPromises","startTimer","remainingTime","Math","max","remainingWait","setTimeout","timerExpired","timeToMaxWait","Date","now","trailingEdge","addEventListener","debounced","Promise","isInvoking","this","push","leadingEdge","set","defineProperties","value","writable","configurable","flush","argsToUse","length","cleanup","delete"],"sourceRoot":""}
|
1
|
+
{"version":3,"file":"index.js","mappings":";;;;;;;;;SAAA;SACA;;;;;UCDA;UACA;UACA;UACA;UACA,yCAAyC,wCAAwC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sBAAsB;IACtB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE;QAC/B,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE;QAC/D,KAAK,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE;QAC7D,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE;QACjE,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE;KACpE,CAAC,CAAC;IAEH,OAAO,SAAS,CAAC;AACrB,CAAC;AAEiE;;;ACrcxC","sources":["webpack://@avatijs/debounce/webpack/bootstrap","webpack://@avatijs/debounce/webpack/runtime/define property getters","webpack://@avatijs/debounce/webpack/runtime/hasOwnProperty shorthand","webpack://@avatijs/debounce/./src/debouce.ts","webpack://@avatijs/debounce/./src/index.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/**\n * Advanced debounce utility with TypeScript support\n * Provides a way to limit the rate at which a function can fire by delaying its execution\n * until after a specified amount of time has elapsed since its last invocation.\n * @module debounce\n */\n\n/**\n * Timer ID type returned by setTimeout\n * Used for managing timers internally\n */\ntype TimerId = ReturnType<typeof setTimeout>;\n\n/**\n * Generic function type that can accept any arguments and return any value\n * Used as a constraint for functions that can be debounced\n */\ntype AnyFunction = (...args: any[]) => any;\n\n/**\n * Configuration options for the debounce function\n * @interface DebounceOptions\n */\ninterface DebounceOptions {\n /** Number of milliseconds to delay execution (default: 0) */\n readonly wait?: number;\n /** Whether to execute on the leading edge of the timeout (default: false) */\n readonly leading?: boolean;\n /** Whether to execute on the trailing edge of the timeout (default: true) */\n readonly trailing?: boolean;\n /** Maximum time the function can be delayed before forced execution */\n readonly maxWait?: number;\n /** Enable debug logging for troubleshooting */\n readonly debug?: boolean;\n /** AbortController signal for cancellation */\n readonly signal?: AbortSignal;\n\n onError?: (error: Error) => void;\n}\n\n/**\n * Interface for the debounced function, including utility methods\n * @interface DebouncedFunction\n * @template T - The type of the original function\n */\ninterface DebouncedFunction<T extends AnyFunction> {\n /** Cancels any pending function invocations */\n readonly cancel: () => void;\n /** Immediately executes any pending function call */\n readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n /** Checks if there are any pending invocations */\n readonly pending: () => boolean;\n /** Cleans up resources used by the debounced function */\n readonly cleanup: () => void;\n\n /** The debounced function that wraps the original */\n (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n/**\n * Internal state management for the debounced function\n * @interface PrivateState\n * @template T - The type of the original function\n * @private\n */\ninterface PrivateState<T extends AnyFunction> {\n /** Current timer ID for the debounce delay */\n timerId?: TimerId;\n /** Timer ID for the maximum wait limit */\n maxTimerId?: TimerId;\n /** Timestamp of the last function call */\n lastCallTime?: number;\n /** Timestamp of the last successful function invocation */\n lastInvokeTime: number;\n /** Arguments from the most recent function call */\n lastArgs?: Parameters<T>;\n /** Execution context (this) from the most recent call */\n lastThis?: any;\n /** Result from the last function execution */\n result?: Awaited<ReturnType<T>>;\n /** Array of pending promises waiting for resolution */\n pendingPromises: Array<{\n resolve: (value: Awaited<ReturnType<T>>) => void;\n reject: (reason?: any) => void;\n }>;\n /** Flag indicating if the function has been aborted */\n aborted: boolean;\n}\n\n/** WeakMap to store private state for each debounced function */\nconst privateState = new WeakMap<DebouncedFunction<any>, PrivateState<any>>();\n\n/**\n * Creates a logger instance based on debug flag\n * @param debug - Whether debug logging is enabled\n * @returns Object with logging methods\n * @private\n */\nconst createLogger = (debug: boolean) => ({\n log: (...args: any[]) => debug && console.log('[Debounce]', ...args),\n warn: (...args: any[]) => debug && console.warn('[Debounce]', ...args),\n error: (...args: any[]) => debug && console.error('[Debounce]', ...args),\n});\n\n/**\n * Creates a debounced version of the provided function that delays invoking func until after\n * wait milliseconds have elapsed since the last time the debounced function was invoked.\n *\n * @template T - The type of the function to debounce\n * @param {T} func - The function to debounce\n * @param {DebounceOptions} [options={}] - Configuration options\n * @returns {DebouncedFunction<T>} The debounced function\n * @throws {TypeError} If func is not a function\n * @throws {RangeError} If wait or maxWait values are invalid\n * @throws {Error} If neither leading nor trailing is true\n *\n * @example\n * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });\n * await debouncedFn(5); // Will execute after 1000ms of inactivity\n * const debouncedFn = debounce(\n * async (x: number) => x * 2,\n * {\n * wait: 1000,\n * onError: (error) => console.error('Error in debounced function:', error)\n * }\n * );\n */\nfunction debounce<T extends AnyFunction>(\n func: T,\n options: DebounceOptions = {},\n): DebouncedFunction<T> {\n // Input validation\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n const {\n wait = 0,\n leading = false,\n trailing = true,\n maxWait,\n debug = false,\n signal,\n onError,\n } = options;\n\n // Validate options\n if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {\n throw new RangeError('Invalid wait/maxWait values');\n }\n\n if (!leading && !trailing) {\n throw new Error('At least one of leading or trailing must be true');\n }\n\n const logger = createLogger(debug);\n const state: PrivateState<T> = {\n lastInvokeTime: 0,\n pendingPromises: [],\n aborted: false,\n };\n\n // Setup abort controller handling\n if (signal) {\n signal.addEventListener('abort', () => {\n state.aborted = true;\n cancel();\n });\n }\n\n /**\n * Cancels all active timers\n * @private\n */\n function cancelTimers(): void {\n if (state.timerId !== undefined) {\n clearTimeout(state.timerId);\n state.timerId = undefined;\n logger.log('Cleared debounce timer');\n }\n if (state.maxTimerId !== undefined) {\n clearTimeout(state.maxTimerId);\n state.maxTimerId = undefined;\n logger.log('Cleared max wait timer');\n }\n }\n\n /**\n * Cancels any pending function invocations\n * Rejects all pending promises and resets internal state\n */\n function cancel(): void {\n logger.log('Cancelling pending invocations');\n cancelTimers();\n state.lastInvokeTime = 0;\n state.lastArgs = undefined;\n state.lastThis = undefined;\n state.lastCallTime = undefined;\n const error = new Error('Debounced function cancelled');\n handleError(error);\n state.pendingPromises.forEach(({ reject }) =>\n reject(new Error('Debounced function cancelled')),\n );\n state.pendingPromises = [];\n }\n\n /**\n * Handles errors during function execution\n * @param {Error} error - The error that occurred\n * @private\n */\n function handleError(error: Error): void {\n logger.error('Error occurred:', error);\n if (onError) {\n try {\n onError(error);\n } catch (callbackError) {\n logger.error('Error in onError callback:', callbackError);\n }\n }\n }\n\n /**\n * Checks if there are any pending function invocations\n * @returns {boolean} True if there are pending invocations\n */\n function pending(): boolean {\n return state.timerId !== undefined;\n }\n\n /**\n * Determines if the function should be invoked based on timing conditions\n * @param {number} time - Current timestamp\n * @returns {boolean} True if function should be invoked\n * @private\n */\n function shouldInvoke(time: number): boolean {\n if (state.aborted) return false;\n\n const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;\n const timeSinceLastInvoke = time - state.lastInvokeTime;\n\n return (\n state.lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxWait !== undefined && timeSinceLastInvoke >= maxWait)\n );\n }\n\n /**\n * Executes the underlying function and manages promise resolution\n * @param {number} time - Current timestamp\n * @returns {Promise} Promise resolving to function result\n * @private\n */\n async function invokeFunc(time: number): Promise<Awaited<ReturnType<T>> | void> {\n logger.log(`Invoking function at ${time}`);\n state.lastInvokeTime = time;\n const args = state.lastArgs!;\n const thisArg = state.lastThis;\n\n state.lastArgs = undefined;\n state.lastThis = undefined;\n\n try {\n const result = await func.apply(thisArg, args);\n state.result = result;\n state.pendingPromises.forEach(({ resolve }) => resolve(result));\n state.pendingPromises = [];\n logger.log('Function invoked successfully', result);\n return result;\n } catch (error) {\n const wrappedError = error instanceof Error ? error : new Error(String(error));\n logger.error('Error in function invocation:', wrappedError);\n handleError(wrappedError);\n\n // Clear pending promises after handling error\n const currentPromises = [...state.pendingPromises];\n state.pendingPromises = [];\n\n // Reject all pending promises\n currentPromises.forEach(({ reject }) => reject(wrappedError));\n }\n }\n\n /**\n * Starts both the debounce timer and maxWait timer if configured\n * @param {number} time - Current timestamp\n * @private\n */\n function startTimer(time: number): void {\n const remainingTime = remainingWait(time);\n state.timerId = setTimeout(timerExpired, remainingTime);\n logger.log(`Started debounce timer for ${remainingTime}ms`);\n\n if (maxWait !== undefined && !state.maxTimerId) {\n const timeToMaxWait = maxWait - (time - state.lastCallTime!);\n state.maxTimerId = setTimeout(\n () => {\n logger.log('Max wait timer expired');\n cancelTimers();\n invokeFunc(Date.now());\n },\n Math.max(0, timeToMaxWait),\n );\n logger.log(`Started max wait timer for ${timeToMaxWait}ms`);\n }\n }\n\n /**\n * Calculates remaining wait time before next execution\n * @param {number} time - Current timestamp\n * @returns {number} Milliseconds until next allowed execution\n * @private\n */\n function remainingWait(time: number): number {\n const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;\n return Math.max(0, wait - timeSinceLastCall);\n }\n\n /**\n * Handles timer expiration\n * @private\n */\n function timerExpired(): void {\n const time = Date.now();\n logger.log('Debounce timer expired');\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n\n startTimer(time);\n }\n\n /**\n * Handles leading edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function leadingEdge(time: number): void {\n logger.log('Leading edge triggered');\n state.lastInvokeTime = time;\n startTimer(time);\n\n if (leading) {\n invokeFunc(time);\n }\n }\n\n /**\n * Handles trailing edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function trailingEdge(time: number): void {\n logger.log('Trailing edge triggered');\n cancelTimers();\n\n if (trailing && state.lastArgs) {\n invokeFunc(time);\n } else {\n state.pendingPromises.forEach(({ resolve }) => {\n resolve(state.result as Awaited<ReturnType<T>>);\n });\n state.pendingPromises = [];\n }\n }\n\n /**\n * Immediately executes the debounced function\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n async function flush(...args: Parameters<T>): Promise<Awaited<ReturnType<T>> | void> {\n logger.log('Flush requested');\n const argsToUse = args.length > 0 ? args : state.lastArgs;\n const thisArg = state.lastThis;\n\n cancelTimers();\n\n if (argsToUse) {\n state.lastArgs = argsToUse;\n state.lastThis = thisArg;\n return invokeFunc(Date.now());\n }\n\n return Promise.resolve(state.result!);\n }\n\n /**\n * Cleans up resources used by the debounced function\n */\n function cleanup(): void {\n logger.log('Cleanup initiated');\n cancel();\n privateState.delete(debounced);\n }\n\n /**\n * The debounced function that wraps the original\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n const debounced = function(\n this: any,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n if (state.aborted) {\n return Promise.reject(new Error('Debounced function aborted'));\n }\n\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n state.lastArgs = args;\n state.lastThis = this;\n state.lastCallTime = time;\n\n logger.log('Function called', {\n time,\n isInvoking,\n args,\n pending: pending(),\n });\n\n return new Promise((resolve, reject) => {\n state.pendingPromises.push({ resolve, reject });\n\n if (state.timerId === undefined) {\n leadingEdge(time);\n } else {\n cancelTimers();\n startTimer(time);\n }\n });\n } as DebouncedFunction<T>;\n\n // Store private state\n privateState.set(debounced, state);\n\n // Add utility methods\n Object.defineProperties(debounced, {\n cancel: { value: cancel, writable: false, configurable: false },\n flush: { value: flush, writable: false, configurable: false },\n pending: { value: pending, writable: false, configurable: false },\n cleanup: { value: cleanup, writable: false, configurable: false },\n });\n\n return debounced;\n}\n\nexport { debounce, type DebouncedFunction, type DebounceOptions };\n","export * from './debouce';\n"],"names":[],"sourceRoot":""}
|
@@ -0,0 +1,7 @@
|
|
1
|
+
/*!
|
2
|
+
* @avatijs/debounce 0.1.3
|
3
|
+
* Copyright (c) 2024 Khaled Sameer <khaled.smq@hotmail.com>
|
4
|
+
* Licensed under MIT, https://opensource.org/licenses/MIT/
|
5
|
+
* Please visit https://avati.io/ for details.
|
6
|
+
*/var e={d:(n,r)=>{for(var o in r)e.o(r,o)&&!e.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:r[o]})},o:(e,n)=>Object.prototype.hasOwnProperty.call(e,n)},n={};e.d(n,{s:()=>t});const r=new WeakMap,o=e=>({log:(...n)=>e&&void 0,warn:(...n)=>e&&void 0,error:(...n)=>e&&void 0});function t(e,n={}){if("function"!=typeof e)throw new TypeError("Expected a function");const{wait:t=0,leading:i=!1,trailing:c=!0,maxWait:a,debug:u=!1,signal:d,onError:l}=n;if(0>t||void 0!==a&&t>a)throw new RangeError("Invalid wait/maxWait values");if(!i&&!c)throw Error("At least one of leading or trailing must be true");const s=o(u),f={lastInvokeTime:0,pendingPromises:[],aborted:!1};function v(){void 0!==f.timerId&&(clearTimeout(f.timerId),f.timerId=void 0,s.log("Cleared debounce timer")),void 0!==f.maxTimerId&&(clearTimeout(f.maxTimerId),f.maxTimerId=void 0,s.log("Cleared max wait timer"))}function g(){s.log("Cancelling pending invocations"),v(),f.lastInvokeTime=0,f.lastArgs=void 0,f.lastThis=void 0,f.lastCallTime=void 0,b(Error("Debounced function cancelled")),f.pendingPromises.forEach((({reject:e})=>e(Error("Debounced function cancelled")))),f.pendingPromises=[]}function b(e){if(s.error("Error occurred:",e),l)try{l(e)}catch(e){s.error("Error in onError callback:",e)}}function m(){return void 0!==f.timerId}function w(e){if(f.aborted)return!1;const n=void 0===f.lastCallTime?0:e-f.lastCallTime;return void 0===f.lastCallTime||n>=t||0>n||void 0!==a&&e-f.lastInvokeTime>=a}async function E(n){s.log("Invoking function at "+n),f.lastInvokeTime=n;const r=f.lastArgs,o=f.lastThis;f.lastArgs=void 0,f.lastThis=void 0;try{const n=await e.apply(o,r);return f.result=n,f.pendingPromises.forEach((({resolve:e})=>e(n))),f.pendingPromises=[],s.log("Function invoked successfully",n),n}catch(e){const n=e instanceof Error?e:Error(e+"");s.error("Error in function invocation:",n),b(n);const r=[...f.pendingPromises];f.pendingPromises=[],r.forEach((({reject:e})=>e(n)))}}function p(e){const n=function(e){return Math.max(0,t-(f.lastCallTime?e-f.lastCallTime:0))}(e);if(f.timerId=setTimeout(h,n),s.log(`Started debounce timer for ${n}ms`),void 0!==a&&!f.maxTimerId){const n=a-(e-f.lastCallTime);f.maxTimerId=setTimeout((()=>{s.log("Max wait timer expired"),v(),E(Date.now())}),Math.max(0,n)),s.log(`Started max wait timer for ${n}ms`)}}function h(){const e=Date.now();if(s.log("Debounce timer expired"),w(e))return function(e){s.log("Trailing edge triggered"),v(),c&&f.lastArgs?E(e):(f.pendingPromises.forEach((({resolve:e})=>{e(f.result)})),f.pendingPromises=[])}(e);p(e)}d&&d.addEventListener("abort",(()=>{f.aborted=!0,g()}));const x=function(...e){if(f.aborted)return Promise.reject(Error("Debounced function aborted"));const n=Date.now(),r=w(n);return f.lastArgs=e,f.lastThis=this,f.lastCallTime=n,s.log("Function called",{time:n,isInvoking:r,args:e,pending:m()}),new Promise(((e,r)=>{f.pendingPromises.push({resolve:e,reject:r}),void 0===f.timerId?function(e){s.log("Leading edge triggered"),f.lastInvokeTime=e,p(e),i&&E(e)}(n):(v(),p(n))}))};return r.set(x,f),Object.defineProperties(x,{cancel:{value:g,writable:!1,configurable:!1},flush:{value:async function(...e){s.log("Flush requested");const n=e.length>0?e:f.lastArgs,r=f.lastThis;return v(),n?(f.lastArgs=n,f.lastThis=r,E(Date.now())):Promise.resolve(f.result)},writable:!1,configurable:!1},pending:{value:m,writable:!1,configurable:!1},cleanup:{value:function(){s.log("Cleanup initiated"),g(),r.delete(x)},writable:!1,configurable:!1}}),x}var i=n.s;export{i as debounce};
|
7
|
+
//# sourceMappingURL=index.min.js.map
|
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B,EAAOlB,IAAI,0BACXmB,EAAMC,eAAiBiB,EACvBW,EAAWX,GAEP3B,GACA8B,EAAWH,EAEnB,CAkFY4B,CAAY5B,IAEZd,IACAyB,EAAWX,GACf,GAER,EAaA,OAVAzC,EAAasE,IAAIN,EAAWzC,GAG5BhC,OAAOgF,iBAAiBP,EAAW,CAC/BjC,OAAQ,CAAEyC,MAAOzC,EAAQ0C,UAAU,EAAOC,cAAc,GACxDC,MAAO,CAAEH,MAtEb7B,kBAAwBtC,GACpBiB,EAAOlB,IAAI,mBACX,MAAMwE,EAAYvE,EAAKwE,OAAS,EAAIxE,EAAOkB,EAAMS,SAC3Ca,EAAUtB,EAAMU,SAItB,OAFAN,IAEIiD,GACArD,EAAMS,SAAW4C,EACjBrD,EAAMU,SAAWY,EACVD,EAAWgB,KAAKC,QAGpBI,QAAQjB,QAAQzB,EAAMuB,OACjC,EAwD2B2B,UAAU,EAAOC,cAAc,GACtDnC,QAAS,CAAEiC,MAAOjC,EAASkC,UAAU,EAAOC,cAAc,GAC1DI,QAAS,CAAEN,MArDf,WACIlD,EAAOlB,IAAI,qBACX2B,IACA/B,EAAa+E,OAAOf,EACxB,EAiD+BS,UAAU,EAAOC,cAAc,KAGvDV,CACX,C","sources":["webpack://@avatijs/debounce/webpack/bootstrap","webpack://@avatijs/debounce/webpack/runtime/define property getters","webpack://@avatijs/debounce/webpack/runtime/hasOwnProperty shorthand","webpack://@avatijs/debounce/./src/debouce.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/**\n * Advanced debounce utility with TypeScript support\n * Provides a way to limit the rate at which a function can fire by delaying its execution\n * until after a specified amount of time has elapsed since its last invocation.\n * @module debounce\n */\n\n/**\n * Timer ID type returned by setTimeout\n * Used for managing timers internally\n */\ntype TimerId = ReturnType<typeof setTimeout>;\n\n/**\n * Generic function type that can accept any arguments and return any value\n * Used as a constraint for functions that can be debounced\n */\ntype AnyFunction = (...args: any[]) => any;\n\n/**\n * Configuration options for the debounce function\n * @interface DebounceOptions\n */\ninterface DebounceOptions {\n /** Number of milliseconds to delay execution (default: 0) */\n readonly wait?: number;\n /** Whether to execute on the leading edge of the timeout (default: false) */\n readonly leading?: boolean;\n /** Whether to execute on the trailing edge of the timeout (default: true) */\n readonly trailing?: boolean;\n /** Maximum time the function can be delayed before forced execution */\n readonly maxWait?: number;\n /** Enable debug logging for troubleshooting */\n readonly debug?: boolean;\n /** AbortController signal for cancellation */\n readonly signal?: AbortSignal;\n\n onError?: (error: Error) => void;\n}\n\n/**\n * Interface for the debounced function, including utility methods\n * @interface DebouncedFunction\n * @template T - The type of the original function\n */\ninterface DebouncedFunction<T extends AnyFunction> {\n /** Cancels any pending function invocations */\n readonly cancel: () => void;\n /** Immediately executes any pending function call */\n readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;\n /** Checks if there are any pending invocations */\n readonly pending: () => boolean;\n /** Cleans up resources used by the debounced function */\n readonly cleanup: () => void;\n\n /** The debounced function that wraps the original */\n (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;\n}\n\n/**\n * Internal state management for the debounced function\n * @interface PrivateState\n * @template T - The type of the original function\n * @private\n */\ninterface PrivateState<T extends AnyFunction> {\n /** Current timer ID for the debounce delay */\n timerId?: TimerId;\n /** Timer ID for the maximum wait limit */\n maxTimerId?: TimerId;\n /** Timestamp of the last function call */\n lastCallTime?: number;\n /** Timestamp of the last successful function invocation */\n lastInvokeTime: number;\n /** Arguments from the most recent function call */\n lastArgs?: Parameters<T>;\n /** Execution context (this) from the most recent call */\n lastThis?: any;\n /** Result from the last function execution */\n result?: Awaited<ReturnType<T>>;\n /** Array of pending promises waiting for resolution */\n pendingPromises: Array<{\n resolve: (value: Awaited<ReturnType<T>>) => void;\n reject: (reason?: any) => void;\n }>;\n /** Flag indicating if the function has been aborted */\n aborted: boolean;\n}\n\n/** WeakMap to store private state for each debounced function */\nconst privateState = new WeakMap<DebouncedFunction<any>, PrivateState<any>>();\n\n/**\n * Creates a logger instance based on debug flag\n * @param debug - Whether debug logging is enabled\n * @returns Object with logging methods\n * @private\n */\nconst createLogger = (debug: boolean) => ({\n log: (...args: any[]) => debug && console.log('[Debounce]', ...args),\n warn: (...args: any[]) => debug && console.warn('[Debounce]', ...args),\n error: (...args: any[]) => debug && console.error('[Debounce]', ...args),\n});\n\n/**\n * Creates a debounced version of the provided function that delays invoking func until after\n * wait milliseconds have elapsed since the last time the debounced function was invoked.\n *\n * @template T - The type of the function to debounce\n * @param {T} func - The function to debounce\n * @param {DebounceOptions} [options={}] - Configuration options\n * @returns {DebouncedFunction<T>} The debounced function\n * @throws {TypeError} If func is not a function\n * @throws {RangeError} If wait or maxWait values are invalid\n * @throws {Error} If neither leading nor trailing is true\n *\n * @example\n * const debouncedFn = debounce(async (x: number) => x * 2, { wait: 1000 });\n * await debouncedFn(5); // Will execute after 1000ms of inactivity\n * const debouncedFn = debounce(\n * async (x: number) => x * 2,\n * {\n * wait: 1000,\n * onError: (error) => console.error('Error in debounced function:', error)\n * }\n * );\n */\nfunction debounce<T extends AnyFunction>(\n func: T,\n options: DebounceOptions = {},\n): DebouncedFunction<T> {\n // Input validation\n if (typeof func !== 'function') {\n throw new TypeError('Expected a function');\n }\n\n const {\n wait = 0,\n leading = false,\n trailing = true,\n maxWait,\n debug = false,\n signal,\n onError,\n } = options;\n\n // Validate options\n if (wait < 0 || (maxWait !== undefined && maxWait < wait)) {\n throw new RangeError('Invalid wait/maxWait values');\n }\n\n if (!leading && !trailing) {\n throw new Error('At least one of leading or trailing must be true');\n }\n\n const logger = createLogger(debug);\n const state: PrivateState<T> = {\n lastInvokeTime: 0,\n pendingPromises: [],\n aborted: false,\n };\n\n // Setup abort controller handling\n if (signal) {\n signal.addEventListener('abort', () => {\n state.aborted = true;\n cancel();\n });\n }\n\n /**\n * Cancels all active timers\n * @private\n */\n function cancelTimers(): void {\n if (state.timerId !== undefined) {\n clearTimeout(state.timerId);\n state.timerId = undefined;\n logger.log('Cleared debounce timer');\n }\n if (state.maxTimerId !== undefined) {\n clearTimeout(state.maxTimerId);\n state.maxTimerId = undefined;\n logger.log('Cleared max wait timer');\n }\n }\n\n /**\n * Cancels any pending function invocations\n * Rejects all pending promises and resets internal state\n */\n function cancel(): void {\n logger.log('Cancelling pending invocations');\n cancelTimers();\n state.lastInvokeTime = 0;\n state.lastArgs = undefined;\n state.lastThis = undefined;\n state.lastCallTime = undefined;\n const error = new Error('Debounced function cancelled');\n handleError(error);\n state.pendingPromises.forEach(({ reject }) =>\n reject(new Error('Debounced function cancelled')),\n );\n state.pendingPromises = [];\n }\n\n /**\n * Handles errors during function execution\n * @param {Error} error - The error that occurred\n * @private\n */\n function handleError(error: Error): void {\n logger.error('Error occurred:', error);\n if (onError) {\n try {\n onError(error);\n } catch (callbackError) {\n logger.error('Error in onError callback:', callbackError);\n }\n }\n }\n\n /**\n * Checks if there are any pending function invocations\n * @returns {boolean} True if there are pending invocations\n */\n function pending(): boolean {\n return state.timerId !== undefined;\n }\n\n /**\n * Determines if the function should be invoked based on timing conditions\n * @param {number} time - Current timestamp\n * @returns {boolean} True if function should be invoked\n * @private\n */\n function shouldInvoke(time: number): boolean {\n if (state.aborted) return false;\n\n const timeSinceLastCall = state.lastCallTime === undefined ? 0 : time - state.lastCallTime;\n const timeSinceLastInvoke = time - state.lastInvokeTime;\n\n return (\n state.lastCallTime === undefined ||\n timeSinceLastCall >= wait ||\n timeSinceLastCall < 0 ||\n (maxWait !== undefined && timeSinceLastInvoke >= maxWait)\n );\n }\n\n /**\n * Executes the underlying function and manages promise resolution\n * @param {number} time - Current timestamp\n * @returns {Promise} Promise resolving to function result\n * @private\n */\n async function invokeFunc(time: number): Promise<Awaited<ReturnType<T>> | void> {\n logger.log(`Invoking function at ${time}`);\n state.lastInvokeTime = time;\n const args = state.lastArgs!;\n const thisArg = state.lastThis;\n\n state.lastArgs = undefined;\n state.lastThis = undefined;\n\n try {\n const result = await func.apply(thisArg, args);\n state.result = result;\n state.pendingPromises.forEach(({ resolve }) => resolve(result));\n state.pendingPromises = [];\n logger.log('Function invoked successfully', result);\n return result;\n } catch (error) {\n const wrappedError = error instanceof Error ? error : new Error(String(error));\n logger.error('Error in function invocation:', wrappedError);\n handleError(wrappedError);\n\n // Clear pending promises after handling error\n const currentPromises = [...state.pendingPromises];\n state.pendingPromises = [];\n\n // Reject all pending promises\n currentPromises.forEach(({ reject }) => reject(wrappedError));\n }\n }\n\n /**\n * Starts both the debounce timer and maxWait timer if configured\n * @param {number} time - Current timestamp\n * @private\n */\n function startTimer(time: number): void {\n const remainingTime = remainingWait(time);\n state.timerId = setTimeout(timerExpired, remainingTime);\n logger.log(`Started debounce timer for ${remainingTime}ms`);\n\n if (maxWait !== undefined && !state.maxTimerId) {\n const timeToMaxWait = maxWait - (time - state.lastCallTime!);\n state.maxTimerId = setTimeout(\n () => {\n logger.log('Max wait timer expired');\n cancelTimers();\n invokeFunc(Date.now());\n },\n Math.max(0, timeToMaxWait),\n );\n logger.log(`Started max wait timer for ${timeToMaxWait}ms`);\n }\n }\n\n /**\n * Calculates remaining wait time before next execution\n * @param {number} time - Current timestamp\n * @returns {number} Milliseconds until next allowed execution\n * @private\n */\n function remainingWait(time: number): number {\n const timeSinceLastCall = state.lastCallTime ? time - state.lastCallTime : 0;\n return Math.max(0, wait - timeSinceLastCall);\n }\n\n /**\n * Handles timer expiration\n * @private\n */\n function timerExpired(): void {\n const time = Date.now();\n logger.log('Debounce timer expired');\n\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n\n startTimer(time);\n }\n\n /**\n * Handles leading edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function leadingEdge(time: number): void {\n logger.log('Leading edge triggered');\n state.lastInvokeTime = time;\n startTimer(time);\n\n if (leading) {\n invokeFunc(time);\n }\n }\n\n /**\n * Handles trailing edge execution\n * @param {number} time - Current timestamp\n * @private\n */\n function trailingEdge(time: number): void {\n logger.log('Trailing edge triggered');\n cancelTimers();\n\n if (trailing && state.lastArgs) {\n invokeFunc(time);\n } else {\n state.pendingPromises.forEach(({ resolve }) => {\n resolve(state.result as Awaited<ReturnType<T>>);\n });\n state.pendingPromises = [];\n }\n }\n\n /**\n * Immediately executes the debounced function\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n async function flush(...args: Parameters<T>): Promise<Awaited<ReturnType<T>> | void> {\n logger.log('Flush requested');\n const argsToUse = args.length > 0 ? args : state.lastArgs;\n const thisArg = state.lastThis;\n\n cancelTimers();\n\n if (argsToUse) {\n state.lastArgs = argsToUse;\n state.lastThis = thisArg;\n return invokeFunc(Date.now());\n }\n\n return Promise.resolve(state.result!);\n }\n\n /**\n * Cleans up resources used by the debounced function\n */\n function cleanup(): void {\n logger.log('Cleanup initiated');\n cancel();\n privateState.delete(debounced);\n }\n\n /**\n * The debounced function that wraps the original\n * @param {...Parameters<T>} args - Function arguments\n * @returns {Promise<ReturnType<T>>} Promise resolving to function result\n */\n const debounced = function(\n this: any,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n if (state.aborted) {\n return Promise.reject(new Error('Debounced function aborted'));\n }\n\n const time = Date.now();\n const isInvoking = shouldInvoke(time);\n\n state.lastArgs = args;\n state.lastThis = this;\n state.lastCallTime = time;\n\n logger.log('Function called', {\n time,\n isInvoking,\n args,\n pending: pending(),\n });\n\n return new Promise((resolve, reject) => {\n state.pendingPromises.push({ resolve, reject });\n\n if (state.timerId === undefined) {\n leadingEdge(time);\n } else {\n cancelTimers();\n startTimer(time);\n }\n });\n } as DebouncedFunction<T>;\n\n // Store private state\n privateState.set(debounced, state);\n\n // Add utility methods\n Object.defineProperties(debounced, {\n cancel: { value: cancel, writable: false, configurable: false },\n flush: { value: flush, writable: false, configurable: false },\n pending: { value: pending, writable: false, configurable: false },\n cleanup: { value: cleanup, writable: false, configurable: false },\n });\n\n return debounced;\n}\n\nexport { debounce, type DebouncedFunction, type DebounceOptions };\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","privateState","WeakMap","createLogger","debug","log","args","console","warn","error","debounce","func","options","TypeError","wait","leading","trailing","maxWait","signal","onError","undefined","RangeError","Error","logger","state","lastInvokeTime","pendingPromises","aborted","cancelTimers","timerId","clearTimeout","maxTimerId","cancel","lastArgs","lastThis","lastCallTime","handleError","forEach","reject","callbackError","pending","shouldInvoke","time","timeSinceLastCall","async","invokeFunc","thisArg","result","apply","resolve","wrappedError","String","currentPromises","startTimer","remainingTime","Math","max","remainingWait","setTimeout","timerExpired","timeToMaxWait","Date","now","trailingEdge","addEventListener","debounced","Promise","isInvoking","this","push","leadingEdge","set","defineProperties","value","writable","configurable","flush","argsToUse","length","cleanup","delete"],"sourceRoot":""}
|
package/dist/types/debouce.d.ts
CHANGED
@@ -70,3 +70,4 @@ interface DebouncedFunction<T extends AnyFunction> {
|
|
70
70
|
*/
|
71
71
|
declare function debounce<T extends AnyFunction>(func: T, options?: DebounceOptions): DebouncedFunction<T>;
|
72
72
|
export { debounce, type DebouncedFunction, type DebounceOptions };
|
73
|
+
//# sourceMappingURL=debouce.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"debouce.d.ts","sourceRoot":"","sources":["../../src/debouce.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAQH;;;GAGG;AACH,KAAK,WAAW,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAE3C;;;GAGG;AACH,UAAU,eAAe;IACrB,6DAA6D;IAC7D,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACv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