Skip to content

Instantly share code, notes, and snippets.

@detro
Created June 16, 2011 10:05
Show Gist options
  • Select an option

  • Save detro/1028982 to your computer and use it in GitHub Desktop.

Select an option

Save detro/1028982 to your computer and use it in GitHub Desktop.
sleepsort in (Phantom)JS
// sleepsort.js - Sort integers from the commandline in a very ridiculous way: leveraging timeouts :P
function sleepSort(array, callback) {
var sortedCount = 0,
i, len;
for ( i = 0, len = array.length; i < len; ++i ) {
setTimeout((function(j){
return function() {
console.log(array[j]);
++sortedCount;
(len === sortedCount) && callback();
};
}(i)), array[i]);
}
}
if ( phantom.args < 1 ) {
console.log("Usage: phantomjs sleepsort.js PUT YOUR INTEGERS HERE SEPARATED BY SPACES");
phantom.exit();
} else {
sleepSort(phantom.args, function() {
phantom.exit();
});
}
@nefarioustim

Copy link
Copy Markdown

Much nicer. :P

function sleepSort(array, callback) {
    for ( var i = 0, idx; idx = array[i++]; ) {
        setTimeout((function(num, j){
            return function() {
                console.log(' ' + num + ' '), ( j === array.length-1 ) && callback();
            };
        }(idx, i)), idx);
    }
}

if ( phantom.args < 1 ) {
    console.log("Usage: phantomjs sleepsort.js PUT YOUR INTEGERS HERE SEPARATED BY SPACES");
    phantom.exit();
} else {
    sleepSort(phantom.args, function(){ phantom.exit(); });
}

@detro

detro commented Jun 16, 2011

Copy link
Copy Markdown
Author

I think you stil suffer of my same bug.

That I just fixed and I'll now post :P

@detro

detro commented Jun 16, 2011

Copy link
Copy Markdown
Author

Now it's good.

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