Skip to content

iterate

Iterate over a callback n times

87 bytes

Usage

A bit like forEach meets reduce. Useful for running a function n number of times to generate a value. The _.iterate function takes a count (the number of times to run the callback), a callback function, and an initial value. The callback is run count many times as a reducer and the accumulated value is then returned.

import * as
import _
_
from 'radashi'
const
const value: number
value
=
import _
_
.
iterate<number>(count: number, func: (currentValue: number, iteration: number) => number, initValue: number): number
export iterate

Like a reduce but does not require an array. Only need a number and will iterate the function as many times as specified.

NOTE: This is NOT zero indexed. If you pass count=5 you will get 1, 2, 3, 4, 5 iteration in the callback function.

@seehttps://radashi.js.org/reference/array/iterate

@example

iterate(3, (total, i) => total + i, 0)
// 6

@version12.1.0

iterate
(
4,
(
acc: number
acc
,
idx: number
idx
) => {
return
acc: number
acc
+
idx: number
idx
},
0,
) // => 10

Note, this is NOT zero indexed. If you pass a count of 5 you will get an index of 1, 2, 3, 4, 5 in the callback function.