Skip to content

Instantly share code, notes, and snippets.

@stiekel
Last active March 3, 2017 03:14
Show Gist options
  • Save stiekel/c5c9d8d96224f3c073a72432f1e042bd to your computer and use it in GitHub Desktop.
Save stiekel/c5c9d8d96224f3c073a72432f1e042bd to your computer and use it in GitHub Desktop.
JavaScript Sleep sort
var list = [-1, 3, 15, 133, -3, 2]
function sleepSort(arr) {
var ordered = []
var q = []
function afterWhile (x, resolve) {
ordered.push(x)
return resolve()
}
arr.forEach(n => {
(x => {
q.push(new Promise((resolve, reject) => {
setTimeout(afterWhile, x, x, resolve)
}))
})(n)
})
Promise.all(q).then(() => {
console.log('orderrd', ordered)
})
}
console.log('list', list)
sleepSort(list)
// Result:
// a [ -1, 3, 15, 133, -3, 2 ]
// orderrd [ -1, -3, 2, 3, 15, 133 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment