Skip to content

Instantly share code, notes, and snippets.

@hraban
Last active June 10, 2019 19:13
Show Gist options
  • Save hraban/b90ab62a375ead373acb93c036e868af to your computer and use it in GitHub Desktop.
Save hraban/b90ab62a375ead373acb93c036e868af to your computer and use it in GitHub Desktop.
Interleaving two arrays in Javascript (using iterators & generators)
/**
* 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