Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 8, 2018 02:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rauschma/f7ed80171c62fc354515 to your computer and use it in GitHub Desktop.
Save rauschma/f7ed80171c62fc354515 to your computer and use it in GitHub Desktop.
function* zip(...iterables) {
let iterators = iterables.map(i => i[Symbol.iterator]());
while (true) {
let entries = iterators.map(i => i.next());
let done = entries.some(entry => entry.done);
if (done) break;
yield entries.map(e => e.value);
}
}
let zipped = zip(['a', 'b', 'c'], ['d', 'e', 'f']);
for (let x of zipped) {
console.log(x);
}
// Output:
// ['a', 'd']
// ['b', 'e']
// ['c', 'f']
function zip(...iterables) {
let iterators = iterables.map(i => i[Symbol.iterator]());
let done = false;
return {
[Symbol.iterator]() {
return this;
},
next() {
if (!done) {
let entries = iterators.map(i => i.next());
done = entries.some(entry => entry.done);
if (!done) {
return { value: entries.map(e => e.value) };
}
}
// We are done
return { done: true };
}
}
}
@Prestaul
Copy link

@rauschma, is there a performance benefit of one over the other? Also, how would these compare to zip_no_iterators_either or zip_old_school_loops?

http://jsperf.com/zip

I wish there was a simple jsperf that supported ES6...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment