594 B
594 B
title, type, language, tags, cover, dateModified
| title | type | language | tags | cover | dateModified | |
|---|---|---|---|---|---|---|
| Iterate n times | snippet | javascript |
|
purple-laptop | 2020-10-20T11:21:07+03:00 |
Iterates over a callback n times.
- Use
Function.prototype.call()to callfnntimes or until it returnsfalse. - Omit the last argument,
context, to use anundefinedobject (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