timesLoading saved progress…

times

_.times(n, iteratee) runs a function n times and gathers the results into an array. It's the clean way to build a fixed-size list — times(5, () => 0) for five zeros, times(3, (i) => i * i) for [0, 1, 4] — without hand-writing a loop.

Implement times(n, iteratee). Call iteratee(i) for i from 0 to n - 1, collect each return value into an array, and return it. iteratee defaults to returning the index, so times(3) gives [0, 1, 2].

Signature

function times(n, iteratee = (i) => i) {
  // calls iteratee(0), iteratee(1), ... iteratee(n-1) and returns the results.
}

Examples

times(3, (i) => i * 2); // [0, 2, 4]
times(5, () => 'a');    // ['a', 'a', 'a', 'a', 'a']
times(3);               // [0, 1, 2]  — default iteratee returns the index
times(0, () => 'x');  // []
times(-2, () => 'x'); // []  — n <= 0 produces nothing

Notes

  • Index argumentiteratee is called with the current index i (0-based).
  • Collects results — the returned array holds each call's return value, in order.
  • Default iteratee — when omitted, it returns the index, so times(n) is [0, 1, ..., n-1].
  • n <= 0 — returns an empty array; the iteratee is never called.
  • Fractional n — truncated toward zero, so times(2.9) runs twice.
Loading editor…