Skip to content

Instantly share code, notes, and snippets.

@arnemart
Forked from 140bytes/LICENSE.txt
Last active February 19, 2020 04:53
Show Gist options
  • Save arnemart/4755031 to your computer and use it in GitHub Desktop.
Save arnemart/4755031 to your computer and use it in GitHub Desktop.
SleepSort in 140 bytes of JavaScript
function(array, callback, extract) {
// Function for extracting timeout value from value.
// Default, just use the value itself.
if (!extract) {
extract = function(value) {
return value;
};
}
// Array to store result in
var result = [];
array.forEach(function(value) {
setTimeout(function() {
// Push value to the sorted array after the correct time
result.push(value);
// Send result array to callback when all the elements have been sorted
if (result.length == array.length) {
callback(result);
}
// Use the extracted timeout value as a delay
}, extract(value));
});
}
function(a,c,e){e=e||function(v){return v};var r=[];a.forEach(function(v){setTimeout(function(){r.push(v);r.length==a.length&&c(r)},e(v))})}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "sleepSort",
"description": "Sort an array using the supremely clever sleepSort algorithm.",
"keywords": [
"sort",
"timeout",
"raceconditions"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>1,5,7,10,26,35,90</b></div>
<div>Actual value: <b id="ret1"></b></div>
<div>Expected value: <b>90,35,26,10,7,5,1</b></div>
<div>Actual value: <b id="ret2"></b></div>
<script>
var sleepSort = function(a,c,e){e=e||function(v){return v};var r=[];a.forEach(function(v){setTimeout(function(){r.push(v);r.length==a.length&&c(r)},e(v))})}
sleepSort([10,90,35,1,5,7,26], function(result) {
document.getElementById( "ret1" ).innerHTML = result.join(',');
});
sleepSort([10,90,35,1,5,7,26], function(result) {
document.getElementById( "ret2" ).innerHTML = result.join(',');
}, function(v) {
return 100 - v;
});
</script>
@atk
Copy link

atk commented Feb 13, 2013

Shortened ot 115 bytes:

function(a,c,e,r){r=[];a.forEach(function(v){setTimeout(function(){r.push(v);r.length==a.length&&c(r)},e?e(v):v)})}

And a version without forEach (which is not present in older browsers):

function(a,c,e,i,r,v){r=[];for(i in a)setTimeout(function(v){return function(){r.push(v);r.length==a.length&&c(r)}}(a[i]),e?e(a[i]):a[i])}

@shinsenter
Copy link

program will wait too long to response when given array contains large numbers, for example [100000, 0, 3, 4000], OMG I do not wait for about 15 minutes for sorted array!

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