Last active
October 30, 2022 11:48
-
-
Save rhysd/6549ae2948b82528655fc640b2e2f36c to your computer and use it in GitHub Desktop.
How to create Iterable object which chains JavaScript Iterator objects
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
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