Aller au contenu principal

times()

times<T>(n, iteratee): T[]

times(n): number[]

Invokes a function n times, returning an array of the results.

remarque

Without iteratee, returns [0, 1, 2, ..., n-1].


Type Parameters

T: T

The type of elements returned by the iteratee.


Parameters

Overload 1:

n: number

The number of times to invoke (must be a non-negative integer).

iteratee: (index) => T

The function to invoke for each index. Defaults to identity (returns indices).

Overload 2:

n: number

The number of times to invoke (must be a non-negative integer).


Returns: T[]

An array containing the results of invoking iteratee n times.


Throws

RangeError If n is negative or not an integer.


Since

2.0.0


Performance

O(n) time & space. Uses for loop with pre-allocated array and early return for n === 0.


Also known as

list (Radashi) · times (Lodash, es-toolkit, Remeda, Ramda, Modern Dash) · ❌ (Effect, Antfu)


Example

times(3);                      // => [0, 1, 2]
times(3, (index) => index * 2); // => [0, 2, 4]
times(3, (index) => `item-${index}`); // => ['item-0', 'item-1', 'item-2']
times(3, () => 'x'); // => ['x', 'x', 'x']

How it works?

Invokes a function n times, returning an array of results.

Usage Patterns

CallResult
times(3)[0, 1, 2]
times(3, index => index * 2)[0, 2, 4]
times(3, index => 'item-' + index)['item-0', 'item-1', 'item-2']
times(3, () => 'x')['x', 'x', 'x']

Process

Without Iteratee

Returns indices when no iteratee is provided.


Use Cases

Repeat operations 📌

Invoke a function n times and collect the results. Cleaner than for loops or Array.from({ length: n }).

const ids = times(5, (index) => `id-${index}`);
// ['id-0', 'id-1', 'id-2', 'id-3', 'id-4']

Generate test fixtures

Create multiple mock objects for testing.

const mockUsers = times(10, (index) => ({
id: index,
name: `User ${index}`,
email: `user${index}@test.com`
}));

Initialize grid data

Populate matrices or grid structures.

const grid = times(rows, (row) =>
times(cols, (col) => ({ row, col, value: null }))
);

Render skeleton loading placeholders

Generate placeholder components while data is loading. Cleaner than manually repeating JSX elements.

const SkeletonList = ({ count }: { count: number }) => (
<ul>
{times(count, (i) => (
<li key={i} className="skeleton-row" aria-hidden="true" />
))}
</ul>
);

// Usage: <SkeletonList count={5} />