Back to Functions

times

util

Invokes the iteratee n times, returning an array of the results of each invocation.

Installation

Import
import { times } from '@tulx/utils';

Source Code

Implementation
/**
 * Invokes the iteratee n times, returning an array of the results of each invocation.
 *
 * @param n - The number of times to invoke iteratee.
 * @param iteratee - The function invoked per iteration.
 * @returns Returns the array of results.
 *
 * @example
 * ```ts
 * times(3, String); // ['0', '1', '2']
 * times(4, () => 0); // [0, 0, 0, 0]
 * ```
 */
export function times<T>(n: number, iteratee: (index: number) => T): T[] {
  const result: T[] = [];
  for (let i = 0; i < n; i++) {
    result.push(iteratee(i));
  }
  return result;
}

Example

import { times } from '@tulx/utils';

times(3, String); // ['0', '1', '2']
times(4, () => 0); // [0, 0, 0, 0]

Related Functions