Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created December 11, 2017 16:20
Show Gist options
  • Save abozhilov/2cdc641cc7fd67a264d359d3d4d67504 to your computer and use it in GitHub Desktop.
Save abozhilov/2cdc641cc7fd67a264d359d3d4d67504 to your computer and use it in GitHub Desktop.
Merge sorted iterators
'use strict';
function* merge(iterable1, iterable2) {
let iter1 = iterable1[Symbol.iterator]();
let iter2 = iterable2[Symbol.iterator]();
let a = iter1.next();
let b = iter2.next();
let isFirst;
while(!a.done && !b.done) {
if (a.value <= b.value) {
yield a.value;
isFirst = true;
}
else {
yield b.value;
isFirst = false;
}
if (isFirst) {
a = iter1.next();
}
else {
b = iter2.next();
}
}
if (!a.done) {
yield a.value;
yield* iter1;
}
if (!b.done) {
yield b.value;
yield* iter2;
}
}
console.log(...merge([1, 3, 9], [2, 5, 11, 15])); //1 2 3 5 9 11 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment