Skip to content

Instantly share code, notes, and snippets.

@rhysd
Last active October 30, 2022 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhysd/6549ae2948b82528655fc640b2e2f36c to your computer and use it in GitHub Desktop.
Save rhysd/6549ae2948b82528655fc640b2e2f36c to your computer and use it in GitHub Desktop.
How to create Iterable object which chains JavaScript Iterator objects
function chained(...iterators) {
return {
[Symbol.iterator]() {
return {
next() {
if (iterators.length === 0) {
return { done: true };
}
const result = iterators[0].next();
if (!result.done) {
return result;
}
iterators.shift();
return this.next();
}
}
}
}
}
const it1 = [1, 2, 3].values();
const it2 = [4, 5, 6].values();
const it3 = [7, 8, 9].values();
for (const i of chained(it1, it2, it3)) {
console.log(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment