Iterate n times
JavaScript, Function · Oct 20, 2020

Iterates over a callback n
times.
- Use
Function.prototype.call()
to callfn
n
times or until it returnsfalse
. - Omit the last argument,
context
, to use anundefined
object (or the global object in non-strict mode).
const times = (n, fn, context = undefined) => {
let i = 0;
while (fn.call(context, i) !== false && ++i < n) {}
};
var output = '';
times(5, i => (output += i));
console.log(output); // 01234