Created
November 6, 2018 00:51
-
-
Save bogstandard/abf860b694950407a0456559c9ed9ef1 to your computer and use it in GitHub Desktop.
SleepSort in JS Array Prototype
This file contains 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
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() |
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);
}
0
s 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
I wrote this in the Chrome Dev Tools console so the formatting is all goofed up, my bad