Skip to content

Instantly share code, notes, and snippets.

@sl
Created August 14, 2017 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sl/a4510fcc231a741f16b8ca7df884213e to your computer and use it in GitHub Desktop.
Save sl/a4510fcc231a741f16b8ca7df884213e to your computer and use it in GitHub Desktop.
Asyncawait Sort
// don't worry about it... it just works
function delay(ms){
var ctr, rej, p = new Promise(function (resolve, reject) {
ctr = setTimeout(() => resolve(ms), ms);
rej = reject;
});
p.cancel = function(){ clearTimeout(ctr); rej(Error("Cancelled"))};
return p;
}
async function sleepSort(arr) {
result = [];
await Promise.all(arr.map(async (x) => {
await delay(x);
result.push(x);
}));
return result;
}
async function main() {
const res = await sleepSort([16, 14, 8, 2, 9, 10, 6, 18, 1, 11, 5, 4, 19, 13, 7, 12, 20, 3, 15, 17]);
console.log(res);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment