Also tormented by a similar question. Or rather, there is a similar task, and there is a need to make it as fast as possible. What is more, it is not just in some kind of cycle, but when events occur ... For example, there are 4 workers and it is necessary for everyone to issue a task for processing. Not sure if this is correct, but I do it something like this:
'use strict'; const Counter = function (array) { if(Array.isArray(array)){ this.current = -1; this.length = array.length; } else { throw new Error(`Can't create instance, non-array value passed.`); } this.next=function(){ this.current+=1; if(this.current>=this.length) this.current=0; return this.current; }; return this; }; let workers = [1,2,3,4,5,6,7,8]; let nextWorker = new Counter(workers); for(let i=0; i<100; i++){ console.log(workers[nextWorker.next()]); }
But let's say it is clumsy and why create a class for it ... But you can either simply allocate a variable with a long length for the necessary arrays ... Or expand the Array prototype and add the iterator functionality to it, just ... a little faster, and most importantly - infinite ...
Array.prototype.next = function () { if(Array.isArray(this) && !this.firstInterationPass){ this.currentElement = -1; this.firstInterationPass = true; } this.currentElement+=1; if(this.currentElement>=this.length) this.currentElement=0; return this[this.currentElement]; }; let workers = [1,2,3,4,5,6,7,8]; for(let i=0; i<100; i++){ console.log(workers.next()); }
As you guess the challenge
worker.next ()
Returns the value of the next element in the array. And the code will output 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,1,2 ...
indexInArray = indexInLoop % 4- Grundy