Created
November 24, 2015 03:08
-
-
Save Tzrlk/5153a1546a6ff4b120b7 to your computer and use it in GitHub Desktop.
Lazy merge sort based on iterator.
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
/* global Symbol */ | |
'use strict'; | |
/** | |
* @param {?} iterable_a | |
* @param {?} [iterable_b] | |
*/ | |
export function mergesortirator(iterable_a, iterable_b) { | |
// Grab the iterator from the provided iterable. | |
const iterator_a = iterable_a[Symbol.iterator]; | |
if (iterable_b) { | |
const iterator_b = iterable_b[Symbol.iterator]; | |
var next_a = null; | |
var next_b = null; | |
return { | |
next: () => { | |
if (!next_a) { | |
next_a = iterator_a.next(); | |
} | |
if (!next_b) { | |
next_b = iterator_b.next(); | |
} | |
if (next_a.done) { | |
if (next_b.done) { | |
return { | |
done: true | |
}; | |
} | |
const returned = next_b; | |
next_b = null; | |
return { | |
value: returned, | |
done: false | |
}; | |
} | |
if (next_b.done) { | |
const returned = next_a; | |
next_a = null; | |
return { | |
value: returned, | |
done: false | |
}; | |
} | |
if (greater(next_a, next_b)) { | |
const returned = next_a; | |
next_a = null; | |
return { | |
value: returned, | |
done: false | |
}; | |
} | |
const returned = next_b; | |
next_b = null; | |
return { | |
value: returned, | |
done: false | |
}; | |
} | |
}; | |
} | |
return { | |
next: function() { | |
const next = iterator_a.next(); | |
if (next.done) { | |
return next; | |
} | |
return { | |
value: null, | |
done: false | |
}; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment