Skip to content

Instantly share code, notes, and snippets.

@therealklanni
Last active February 11, 2020 09:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therealklanni/3ecd367b7191c4a7a6f6 to your computer and use it in GitHub Desktop.
Save therealklanni/3ecd367b7191c4a7a6f6 to your computer and use it in GitHub Desktop.
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