-
-
Save medikoo/ad60a11ddaa3eb23d9cf980969b45a83 to your computer and use it in GitHub Desktop.
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
console.log("1. zip"); | |
for (const [i, x] of zip(naturalNumbers(), naturalNumbers())) { | |
console.log(i, x); | |
} | |
console.log("2. Array.from"); | |
Array.from(naturalNumbers(), function (x, i) { | |
console.log(i, x); | |
}); | |
function* naturalNumbers() { | |
for (let n=0; n < 10; n++) { | |
console.log("Yield", n); | |
yield n; | |
} | |
}; | |
function zip(...iterables) { | |
const iterators = iterables.map(i => i[Symbol.iterator]()); | |
let done = false; | |
return { | |
[Symbol.iterator]() { | |
return this; | |
}, | |
next() { | |
if (!done) { | |
const items = iterators.map(i => i.next()); | |
done = items.some(item => item.done); | |
if (!done) { | |
return { value: items.map(i => i.value) }; | |
} | |
// Done for the first time: close all iterators | |
for (const iterator of iterators) { | |
if (typeof iterator.return === 'function') { | |
iterator.return(); | |
} | |
} | |
} | |
// We are done | |
return { done: true }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment