I have an array in JavaScript that have defined these values:
var myStringArray = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"];
The fancy solution with generator functions:
function* cycle(arr) {
let i=0;
while (true) {
yield arr[i++];
i %= arr.length;
}
}
function* chunksOf(n, iterable) {
let chunk = [];
for (const x of iterable) {
chunk.push(x)
if (chunk.length >= n) {
yield chunk;
chunk = [];
}
}
if (chunk.length > 0)
yield chunk;
}
function toFunction(iterator) {
return () => iterator.next().value;
}
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
const f = toFunction(chunksOf(3, cycle(myStringArray)));
console.log(f());
console.log(f());
console.log(f());
// …