legends810/testingnew
0
1/**2 * Creates a function that samples calls at regular intervals and captures trailing calls.3 * - Drops calls that occur between sampling intervals4 * - Takes one call per sampling interval if available5 * - Captures the last call if no call was made during the interval6 *7 * @param fn The function to sample8 * @param sampleInterval How often to sample calls (in ms)9 * @returns The sampled function10 */11export function createSampler<T extends (...args: any[]) => any>(fn: T, sampleInterval: number): T {12 let lastArgs: Parameters<T> | null = null;13 let lastTime = 0;14 let timeout: NodeJS.Timeout | null = null;15 16 // Create a function with the same type as the input function17 const sampled = function (this: any, ...args: Parameters<T>) {18 const now = Date.now();19 lastArgs = args;20 21 // If we're within the sample interval, just store the args22 if (now - lastTime < sampleInterval) {23 // Set up trailing call if not already set24 if (!timeout) {25 timeout = setTimeout(26 () => {27 timeout = null;28 lastTime = Date.now();29 30 if (lastArgs) {31 fn.apply(this, lastArgs);32 lastArgs = null;33 }34 },35 sampleInterval - (now - lastTime),36 );37 }38 39 return;40 }41 42 // If we're outside the interval, execute immediately43 lastTime = now;44 fn.apply(this, args);45 lastArgs = null;46 } as T;47 48 return sampled;49}50 