Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 8, 2018 02:25
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rauschma/02ec6acbae1fd3283c65eb8e86dd48ed to your computer and use it in GitHub Desktop.
Save rauschma/02ec6acbae1fd3283c65eb8e86dd48ed to your computer and use it in GitHub Desktop.
// Lazy (=on-demand) zip()
for (const [i, x] of zip(naturalNumbers(), naturalNumbers())) {
console.log(i, x);
if (i >= 2) break;
}
// Output:
// 0 0
// 1 1
// 2 2
// Eager Array.from() (.entries() is lazy)
for (const [i, x] of Array.from(naturalNumbers()).entries()) {
console.log(i, x);
if (i >= 2) break;
}
// Infinite loop
function* naturalNumbers() {
for (let n=0;; 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