All files throttle.ts

94.44% Statements 17/18
75% Branches 3/4
100% Functions 3/3
93.75% Lines 15/16

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                            8x       8x 1x                 1x 1x 10x 10x 1x 1x     1x   9x 9x 9x 9x     9x          
/**
 * The Debounce technique allow us to “group” multiple sequential calls in a single one.
 * @description
 * You can find great article that explains how throttle works [here](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * @param func - Any provided function
 * @param debounceTimeMs - duration in milliseconds
 * @signature
 *    P.throttle(func, throttleTimeMs)
 * @example
 *    // Execute log
 *    P.throttle(console.log, 1000)
 * @category Function
 */
 
import { purry } from "./purry";
 
export function throttle<E extends (...args: any[]) => any>(func: E, throttleTimeMs: number): E 
export function throttle<E extends (...args: any[]) => any>(throttleTimeMs: number): (func: E) => E 
export function throttle() {
  return purry(__throttle, arguments)
}
 
 
function __throttle<Input extends any[], R>(
  func: (...args: Input) => R,
  throttleTimeMs: number
): (...args: Input) => R {
  // tslint:disable: no-let
  let lastExec: number | null = null;
  let result: { readonly r: R } | null = null;
  return (...args) => {
    if (result == null) {
      lastExec = Date.now();
      result = {
        r: func(...args),
      };
      return result.r;
    }
    const diff = Date.now() - lastExec!;
    Eif (diff >= throttleTimeMs) {
      lastExec = Date.now();
      result = {
        r: func(...args),
      };
      return result.r;
    }
    return result.r;
  };
}