Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | 20x 20x 34x 34x 34x 34x 34x 34x 34x 34x 33x 33x 33x 1x 1x 1x 34x 34x 34x 34x 68x 68x 31x 37x 37x 5x 5x 5x 5x 2x 2x 5x 32x 32x 27x 27x 27x 27x 27x 32x 32x 34x 4x 3x 3x 4x 4x 4x 3x 3x 34x 4x 2x 2x 4x 2x 2x 2x 34x | import type { DeferredValue } from './deferred-value.ts'; import { createDeferredValue } from './deferred-value.ts'; import type { Timeout } from './types.ts'; /** * Configuration options for the debounce utility. */ export type DebounceOptions<TArgs extends unknown[] = unknown[]> = { /** * The delay in milliseconds to wait before executing the debounced function. */ readonly delay: number; /** * If true, the function will be called immediately, i.e., on the leading edge of the timeout. If false (default), the * function will be called on the trailing edge. */ readonly leading?: boolean; /** * If true, the debounce will wait for the previous promise to complete before processing new calls. If false * (default), new calls will be debounced immediately regardless of previous promise state. */ readonly waitForPrevious?: boolean; /** * Optional function to accumulate arguments from multiple calls before execution. If provided, instead of using only * the last call's arguments, this function will be called to combine the previous accumulated arguments with the new * call's arguments. * * **Important**: The accumulator function is called immediately on every debounced function call (it is NOT * debounced). Therefore, it should be fast and free of side effects to avoid performance issues. * * @param previousArgs - The previously accumulated arguments (undefined for the first call) * @param currentArgs - The arguments from the current call * @returns The accumulated arguments to use for the next call or final execution */ readonly accumulator?: (previousArgs: TArgs | undefined, currentArgs: TArgs) => [...TArgs]; }; /** * A debounced function that returns a promise. * * @template TArgs - The arguments type of the original function. * @template TReturn - The return type of the original function. */ export type DebouncedFunction<TArgs extends unknown[], TReturn> = { /** * Calls the debounced function and returns a promise that resolves to the result. If the function is called multiple * times within the debounce delay, only the last call will be executed, and all callers will receive the same * result. */ (...args: TArgs): Promise<TReturn>; /** * Cancels any pending debounced function calls. */ cancel(): void; /** * Immediately executes the debounced function with the last provided arguments, bypassing the delay. */ flush(): Promise<TReturn> | undefined; }; /** * Creates a debounced version of a function that supports promises. * * When the debounced function is called multiple times within the delay period, only the last call will be executed. * All callers will receive the same result through their returned promises. * * By default, if the original function returns a promise, new calls will be debounced immediately without waiting. Set * `waitForPrevious: true` to wait for previous promises to complete. * * @example Basic usage * * ```ts * const search = debounce(async (query: string) => { * const response = await fetch(`/api/search?q=${query}`); * return response.json(); * }, 300); * * // These calls will be debounced - only the last one will execute * const result1 = search('hello'); * const result2 = search('hello world'); * const result3 = search('hello world!'); * * // All three promises will resolve to the same result * const [r1, r2, r3] = await Promise.all([result1, result2, result3]); * console.log(r1 === r2 && r2 === r3); // true * ``` * * @example With leading edge execution * * ```ts * const saveData = debounce( * async (data: any) => { * return await api.save(data); * }, * { delay: 1000, leading: true }, * ); * * // First call executes immediately, subsequent calls are debounced * await saveData({ id: 1 }); // Executes immediately * await saveData({ id: 2 }); // Debounced * ``` * * @example With argument accumulation * * ```ts * const batchProcessor = debounce( * async (ids: number[]) => { * return await api.processBatch(ids); * }, * { * delay: 300, * // Accumulator is fast and pure - just combines arrays * accumulator: (prev, current) => { * const prevIds = prev?.[0] || []; * const currentIds = current[0]; * return [[...prevIds, ...currentIds]]; * }, * }, * ); * * batchProcessor([1, 2]); * batchProcessor([3, 4]); * batchProcessor([5]); * // Eventually processes [1, 2, 3, 4, 5] in a single call * ``` * * @example With waiting for previous promises * * ```ts * const sequentialDebounce = debounce( * async (value: string) => { * await longRunningOperation(value); * return `processed: ${value}`; * }, * { delay: 300, waitForPrevious: true }, * ); * * sequentialDebounce('first'); // Starts long operation * sequentialDebounce('second'); // Waits for first to complete before debouncing * ``` * * @template TArgs - The arguments type of the original function. * @template TReturn - The return type of the original function. * @param fn - The function to debounce. * @param options - The debounce delay in millisecond or the configuration options. * @returns A debounced version of the function that returns a promise. */ export const debounce = <TArgs extends unknown[], TReturn>( fn: (...args: TArgs) => TReturn | Promise<TReturn>, options: number | DebounceOptions<TArgs>, ): DebouncedFunction<TArgs, TReturn> => { let timeoutId: Timeout | undefined; let lastArgs: TArgs | undefined; let pendingDeferred: DeferredValue<TReturn> | undefined; let isExecuting = false; let hasLeadingBeenCalled = false; options = typeof options === 'number' ? { delay: Math.max(0, Math.ceil(options)), waitForPrevious: false } : { waitForPrevious: false, ...options, delay: Math.max(0, Math.ceil(options.delay)) }; const executeFunction = async (args: TArgs): Promise<TReturn> => { Iif (isExecuting && options.waitForPrevious) { // If we're already executing a promise and waitForPrevious is true, // wait for it to complete and return the result to all pending callers return pendingDeferred!.promise; } isExecuting = true; try { const result = await fn(...args); Eif (pendingDeferred) { pendingDeferred.resolve(result); } return result; } catch (error) { Eif (pendingDeferred) { pendingDeferred.reject(error); } throw error; } finally { isExecuting = false; pendingDeferred = undefined; lastArgs = undefined; } }; const debouncedFunction = (...args: TArgs): Promise<TReturn> => { // Handle argument accumulation lastArgs = options.accumulator ? options.accumulator(lastArgs, args) : args; // If we already have a pending deferred, reuse it if (pendingDeferred) { return pendingDeferred.promise; } // Create a new deferred for this execution cycle pendingDeferred = createDeferredValue<TReturn>(); // Handle leading edge execution if (options.leading && !hasLeadingBeenCalled && !isExecuting) { hasLeadingBeenCalled = true; // Execute immediately but still set up the timeout for trailing edge reset const promise = executeFunction(args); // Set up timeout to reset leading edge flag Iif (timeoutId !== undefined) { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { hasLeadingBeenCalled = false; timeoutId = undefined; }, options.delay); return promise; } // Clear any existing timeout Iif (timeoutId !== undefined) { clearTimeout(timeoutId); } const debouncedExecution = async () => { timeoutId = undefined; hasLeadingBeenCalled = false; Eif (lastArgs && !isExecuting) { try { await executeFunction(lastArgs); } catch { // Error is already handled by executeFunction through pendingDeferred.reject // No need to re-throw here as it would create an unhandled rejection } } }; timeoutId = setTimeout(() => void debouncedExecution(), options.delay); return pendingDeferred.promise; }; debouncedFunction.cancel = () => { if (timeoutId !== undefined) { clearTimeout(timeoutId); timeoutId = undefined; } hasLeadingBeenCalled = false; lastArgs = undefined; if (pendingDeferred && !pendingDeferred.settled) { pendingDeferred.reject(new Error('Debounced function call was cancelled')); pendingDeferred = undefined; } }; debouncedFunction.flush = (): Promise<TReturn> | undefined => { if (timeoutId !== undefined) { clearTimeout(timeoutId); timeoutId = undefined; } if (lastArgs && !isExecuting) { hasLeadingBeenCalled = false; return executeFunction(lastArgs); } return undefined; }; return debouncedFunction; }; |