A loop with a lot of iterations is given. Dan array with four elements. How beautifully to implement a looping array through the loop as follows:

0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

0 | 1 | 2 | 3 | 0 | 1 | 2 | 3 | 0 | 1, etc.

At the top of the loop iteration, at the bottom of the array elements.

  • 9
    indexInArray = indexInLoop % 4 - Grundy

3 answers 3

In the new js specification there is such a thing as generators, you can use them to support older browsers to use polyfil

Example

 const array = [1, 2, 3, 4]; const generator = function* (arr) { let i = 0 let length = arr.length while(true) { yield arr[i] i++ if(i === length) i = 0 } } // используем const arrayLoop = generator(array) for(let i = 0; i < 1000; i++) { console.log(arrayLoop.next()) // next будет возвращать объект типа // {value, done} // где вам нужно value } 

Approximate answer

     const arr = [1, 2, 3, 4 let count = 0; while(true) { for(el of arr) { console.log(el) count++ } } 

    Make it asynchronous and with a timer, or there will be a very large load.

      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 ...