times()
times<
T>(n,iteratee):T[]
times(
n):number[]
Invokes a function n times, returning an array of the results.
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โ
| Call | Result |
|---|---|
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} />