Created
March 13, 2021 17:00
-
-
Save luavixen/d3d5184c4a687170c992a872dbf9f24a to your computer and use it in GitHub Desktop.
JavaScript sleep sort implementation using async iterators.
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
function race(promises) { | |
return new Promise((resolve, reject) => { | |
for (const promise of promises) | |
if ( | |
promise | |
&& typeof promise === "object" | |
&& typeof promise.then === "function" | |
) promise.then(resolve, reject); | |
}); | |
} | |
function sleep(timeout, value) { | |
return new Promise(resolve => setTimeout(resolve, timeout, value)); | |
} | |
async function collect(iterable) { | |
const values = []; | |
for await (const item of iterable) | |
values.push(item); | |
return values; | |
} | |
async function* sleepSort(iterable, multiple = 100) { | |
const promises = | |
(await collect(iterable)) | |
.map((value, i) => sleep(value * multiple, [value, i])); | |
for (let completed = 0; completed < promises.length; completed++) { | |
const [value, i] = await race(promises); | |
promises[i] = null; | |
yield value; | |
} | |
} | |
// Example | |
(async () => { | |
const numbers = [5, 2, 6, 4, 8, 10, 7, 1, 9, 3]; | |
const sorted = await collect(sleepSort(numbers)); | |
console.log(sorted); // After ~1 second outputs: 1,2,3,4,5,6,7,8,9,10 | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment