Skip to content

Instantly share code, notes, and snippets.

@bogstandard
Created November 6, 2018 00:51
Show Gist options
  • Save bogstandard/abf860b694950407a0456559c9ed9ef1 to your computer and use it in GitHub Desktop.
Save bogstandard/abf860b694950407a0456559c9ed9ef1 to your computer and use it in GitHub Desktop.
SleepSort in JS Array Prototype
Array.prototype.sleepSort = function(){
const timeout = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
const spush = async (n) => {
await timeout(n);
this.shift();
this.push(n);
}
let max = 0;
this.forEach(n => {
if(max < n) max = n;
spush(n);
});
(async function(){await timeout(max)})()
};
let nums = [4000,3000,2000,1000];
nums.sleepSort()
@bogstandard
Copy link
Author

I wrote this in the Chrome Dev Tools console so the formatting is all goofed up, my bad

@bogstandard
Copy link
Author

To get it to reverse sort you could make a method like spush but sunshift which is called instead.

	const sunshift = async (n) => {
		await timeout(n);
		this.pop();
		this.unshift(n);
    }

0s currently don't play nicely with the current implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment