JSFiddle - React, Tailwind, and code Playground
JavaScript
class MultiIterator {
constructor(inp) {
this.inp = inp;
this.x = -1;
this.inpLen = inp.length;
this.levelProgress = Array(inp.length).fill(0);
this.nextX = 0;
}
hasNext() {
var count = 0;
var listIndex = this.x;
var elemIndex;
do {
listIndex++;
listIndex %= this.inpLen;
elemIndex = this.levelProgress[listIndex]; // index = size - 1
count++;
} while (count < this.inpLen && elemIndex === this.inp[listIndex].length)
if (elemIndex === this.inp[listIndex].length) {
return false;
}
this.nextX = listIndex;
return true;
}
next() {
if (this.hasNext()) {
this.x = this.nextX;
this.levelProgress[this.x]++;
return this.inp[this.x][this.levelProgress[this.x] - 1];
}
return null;
}
}
// Test Code
const node = new MultiIterator([
[1, 2],
[],
[4],
[5],
]);
while (node.hasNext()) {
console.log(node.next());
}