Last active
November 26, 2021 11:43
-
-
Save squio/c3822dba48f45bacb3c218cb573e4139 to your computer and use it in GitHub Desktop.
Round robin array iterator in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Round robin array iterator | |
* @param {string | any[]} arr | |
*/ | |
function* RoundRobinArray(arr) { | |
let idx = 0; | |
for (;;) { | |
yield arr[idx]; | |
idx++; | |
if (idx >= arr.length) { | |
idx = 0; | |
} | |
} | |
} | |
// Usage | |
const it = RoundRobinArray(['aaaa', 'bbbb', 'cccc']); | |
for (let i=0; i<10; i++) { | |
console.log(it.next().value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment