Created
May 6, 2015 06:56
-
-
Save raymonstah/af4cb8323afb3878c50d to your computer and use it in GitHub Desktop.
Sleep Sort in JavaScript (No Threads!)
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
// Raymond Ho | |
// JavaScript makes Sleep Sort so easy to implement.. | |
// Exponentially slower if sorting larger numbers. | |
function sleepNumber(number) { | |
// The timeout is (n^2) so that close numbers are no longer close. | |
// Example: 1 is really close to 2, but 1^2 isn't close to 2^2. | |
setTimeout(function(){ | |
console.log(number); | |
}, number*number); | |
} | |
function sleepSort(array) { | |
for (i = 0; i < array.length; ++i){ | |
sleepNumber(array[i]); | |
} | |
} | |
// Generate 100 random numbers for sorting. | |
randoms = []; | |
for (i = 0; i < 100; ++i) { | |
// Random number between 1 - 100 | |
randomInt = Math.floor((Math.random()*100) + 1); | |
randoms.push(randomInt); | |
} | |
// Sort said random numbers. | |
sleepSort(randoms); | |
The real challenge is to implement it such that the function actually returns the array, instead of logging. This is my attempt:
I came across this, and I had to give it a go :)
const sleepSort = async (arr) => {
const result = [];
await Promise.all(
arr.map(async (n) => {
await new Promise((res) => setTimeout(res, n));
result.push(n);
})
);
return result;
};
await sleepSort(sleepSort([11, 4, 1, 6, 3, 7, 9, 5]));
@Brendan-Stubbs It works! but only if the duped call is removed. BTW, thank you! that code has helped me understand async programming better. I seriously need to spend more time learning about that subject.
Since I prefer self-commenting code, I would rewrite it as
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const sleepSort = async (arr) => {
const out = [];
await Promise.all(
arr.map(async (n) => {
await sleep(n);
out.push(n);
})
);
return out;
};
Typescript/Bun implementation:
const sleepSort = async (arr: number[]) => {
const result: number[] = [];
await Promise.all(
arr.map(async (n) => {
await Bun.sleep(n);
result.push(n);
})
);
return result;
};
console.log(await sleepSort([11, 4, 1, 6, 3, 7, 9, 5]));
Interesting! I didn't know Bun has a sleep
API
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The real challenge is to implement it such that the function actually returns the array, instead of logging. This is my attempt:
But it gets stuck in an infinite loop and I have no idea why lol