All files times.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 2/2
100% Lines 9/9

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 428x                                                 8x 15x       18x 6x     12x 12x 42x     12x    
import { purry } from './purry';
 
/**
 * Calls an input function `n` times, returning an array containing the results
 * of those function calls.
 *
 * @description
 * `fn` is passed one argument: The current value of `n`, which begins at `0`
 * and is gradually incremented to `n - 1`.
 *
 * @param count A value between `0` and `n - 1`. Increments after each function call.
 * @param fn The function to invoke. Passed one argument, the current value of `n`.
 * @return An array containing the return values of all calls to `fn`.
 * @throws If count is less than 0
 * @signature
 *    P.times(5, fn)
 * @signature
 *    P.times(fn)(count)
 * @example
 *  P.times(identity, 5); //=> [0, 1, 2, 3, 4]
 * @category Utility, Pipe
 */
export function times<T>(count: number, fn: (n: number) => T): T[];
export function times<T>(fn: (n: number) => T): (count: number) => T[];
 
export function times() {
  return purry(_times, arguments);
}
 
function _times<T>(count: number, fn: (n: number) => T): T[] {
  if (count < 0) {
    throw new RangeError('n must be a non-negative number');
  }
 
  const res = [];
  for (let i = 0; i < count; i++) {
    res.push(fn(i));
  }
 
  return res;
}