-
-
Save abozhilov/2cdc641cc7fd67a264d359d3d4d67504 to your computer and use it in GitHub Desktop.
Merge sorted iterators
This file contains 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
'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