Last active
April 8, 2018 02:26
-
-
Save rauschma/f7ed80171c62fc354515 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
| 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'] |
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 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 }; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@rauschma, is there a performance benefit of one over the other? Also, how would these compare to
zip_no_iterators_eitherorzip_old_school_loops?http://jsperf.com/zip
I wish there was a simple jsperf that supported ES6...