Combining Multiple Iterators
You'll learn how to merge several iterables into one unified iterator using custom logic.
What Does "Combining" Mean?
When you have multiple iterables—like arrays, strings, or custom collections—you sometimes want to treat them as a single sequence. There are two common patterns:
- Chaining (concatenation): iterate through the first iterable completely, then the second, then the third, etc.
- Zipping: take one element from each iterable in turn, pairing them together until one runs out.
Think of chaining like reading three books cover-to-cover in order. Zipping is like shuffling two decks of cards together, alternating one card from each deck.
Chaining Multiple Iterables
function chain(...iterables) {
return {
[Symbol.iterator]() {
let currentIndex = 0;
let currentIterator = iterables[currentIndex][Symbol.iterator]();
return {
next() {
let result = currentIterator.next();
while (result.done && currentIndex < iterables.length - 1) {
currentIndex++;
currentIterator = iterables[currentIndex][Symbol.iterator]();
result = currentIterator.next();
}
return result;
}
};
}
};
}
for (const val of chain([1, 2], [3, 4], [5])) {
console.log(val); // 1, 2, 3, 4, 5
}
Zipping Iterables Together
function zip(...iterables) {
return {
[Symbol.iterator]() {
const iterators = iterables.map(it => it[Symbol.iterator]());
return {
next() {
const results = iterators.map(it => it.next());
if (results.some(r => r.done)) {
return { done: true };
}
return { value: results.map(r => r.value), done: false };
}
};
}
};
}
for (const [a, b] of zip([1, 2, 3], ['a', 'b', 'c'])) {
console.log(a, b); // 1 'a', 2 'b', 3 'c'
}
Key Takeaway: Combining iterators lets you orchestrate multiple data sources into unified iteration patterns—chaining sequences end-to-end or zipping them together element-by-element.