Last active
June 10, 2019 19:13
-
-
Save hraban/b90ab62a375ead373acb93c036e868af to your computer and use it in GitHub Desktop.
Interleaving two arrays in Javascript (using iterators & generators)
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
/** | |
* interleave([1,2], [8,7,6,5], [], 'abc') | |
* => [ 1, 8, 'a', 2, 7, 'b', 6, 'c', 5 ] | |
*/ | |
function* interleave() { | |
const its = Array.from(arguments).map(x => x[Symbol.iterator]()); | |
let done; | |
do { | |
done = true; | |
for (const it of its) { | |
const next = it.next(); | |
if (!next.done) { | |
yield next.value; | |
done = false; | |
} | |
} | |
} while (!done) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment