Files
30-seconds-of-code/snippets/times.md
30secondsofcode 788d625b62 Travis build: 1383
2018-01-24 11:51:58 +00:00

445 B

times

Iterates over a callback n times

Use Function.call() to call fn n times or until it returns false. Omit the last argument, context, to use an undefined 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