All files purry.ts

100% Statements 13/13
90% Branches 9/10
100% Functions 2/2
100% Lines 12/12

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                                                            66x 481x 481x 481x 278x   203x 202x 202x 121x 121x   202x   1x    
/**
 * Creates a function with `data-first` and `data-last` signatures.
 *
 * `purry` is a dynamic function and it's not type safe. It should be wrapped by a function that have proper typings.
 * Refer to the example below for correct usage.
 *
 * @param fn the function to purry.
 * @param args the arguments
 * @signature P.purry(fn, arguments);
 * @example
 *    function _findIndex(array, fn) {
 *      for (let i = 0; i < array.length; i++) {
 *        if (fn(array[i])) {
 *          return i;
 *        }
 *      }
 *      return -1;
 *    }
 *
 *    // data-first
 *    function findIndex<T>(array: T[], fn: (item: T) => boolean): number;
 *
 *    // data-last
 *    function findIndex<T>(fn: (item: T) => boolean): (array: T[]) => number;
 *
 *    function findIndex() {
 *      return P.purry(_findIndex, arguments);
 *    }
 * @category Function
 */
export function purry(fn: any, args: IArguments | readonly any[], lazy?: any) {
  const diff = fn.length - args.length;
  const arrayArgs = Array.from(args);
  if (diff === 0) {
    return fn(...arrayArgs);
  }
  if (diff === 1) {
    const ret: any = (data: any) => fn(data, ...arrayArgs);
    if (lazy || fn.lazy) {
      ret.lazy = lazy || fn.lazy;
      ret.lazyArgs = args;
    }
    return ret;
  }
  throw new Error('Wrong number of arguments');
}