Last active
March 3, 2017 03:14
-
-
Save stiekel/c5c9d8d96224f3c073a72432f1e042bd to your computer and use it in GitHub Desktop.
JavaScript Sleep sort
This file contains hidden or 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
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