nTimes

Calls a function n times and returns an array of the results.

1. Code

const nTimes = <T>(fn: (i: number) => T, n: number = 1): T[] => {
  if (n < 0) {
    throw new Error("n must be greater than 0");
  }
  let result: T[] = [];
  for (let i = 0; i < n; i++) {
    result.push(fn(i));
  }
  return result;
};

export default nTimes;

2. Installation

npx @jrtilak/lazykit@latest add nTimes

3. Description

The nTimes function calls a function n times and returns an array of the results. The function is called with the index of the iteration as the first argument.

4. Props

Prop

Type

Default Value

function*Function---
nnumber1

5. Examples

import nTimes from ".";

const result = nTimes(() => "result", 3);
// Expected: ["result", "result", "result"]

// You can also use the index of the iteration.
const result2 = nTimes((i) => i, 3);
// Expected: [0, 1, 2]