Last active
February 11, 2020 09:39
-
-
Save therealklanni/3ecd367b7191c4a7a6f6 to your computer and use it in GitHub Desktop.
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
function asyncQuicksort(xs = []) { | |
// get the "head" and "tail" of the array | |
let [h, ...t] = xs | |
// create the initial Promise | |
return new Promise((res, rej) => { | |
// resolve immediately if "head" was undefined | |
if (!h) return res([]) | |
// recurse for the "left" half of the partition | |
asyncQuicksort(t.filter(a => a <= h)).then(a => { | |
// recurse for the "right" half of the partition | |
asyncQuicksort(t.filter(a => a > h)).then(b => { | |
// join each half on the pivot and resolve the promise | |
res(a.concat(h, b)) | |
}).catch(rej) // in case your array is too long catch the error | |
}).catch(rej) | |
}) | |
} | |
asyncQuicksort('the quick brown fox jumps over the lazy dog'.split('')) | |
.then(a => log(a.join(''))) | |
.catch(log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment