// ⭐ interleave()
// interleaves the values of a list of iterables
function* interleave(...iterables) {
// iterables -> iterators
let iterators = iterables.map(it => it[Symbol.iterator]());
let i = 0; // index of current iterator
// while still some iterators
while (iterators.length > 0) {
// if last iterator reached, go back to first
if (i >= iterators.length) i = 0;
// get next iteration result of current iterator
let result = iterators[i].next();
if (result.done) { // if current iterator done,
iterators.splice(i, 1); // • remove it.
} else { // otherwise,
yield result.value; // • yield the value
i += 1; // • go to next iterator.
}
}
// all iterators done
return;
}
// export
module.exports = interleave;