News for hackers. Stuff that matters.
Re:Writing a Non-Blocking JavaScript Quicksort by drostie on Wednesday June 10, 2015 @09:05AM (#9691807)
> There’s just one problem – now we’ve made the function asynchronous, how do we know when it has finished?

The most obvious thing is just to call out to a (semi-) global:

    function quicksort(arr, cb) {
        var thread_balance = 1;
        function thread(start, end) {
            if (not trivially solved) {
                partition_stuff;
                thread_balance += 1;
                setImmediate(...);
                setImmediate(...);
            } else {
                thread_balance -= 1; // this thread is done.
                if (thread_balance === 0) {
                    cb(arr);
                }
            }
        }
        thread(0, arr.length);
    }
This is why concurrent datatypes are often interested in simple registers that you can only increment/decrement, they are still super-helpful for coordinating when a workload is complete.

Taking this a little further, we can wrap setInterval in a Promises library which gives you back a promise for the sorted halves of the array; the thread(start, end) promise resolves with the [start..end-1] indices being sorted, and in the nontrivial case returns Promise.all([thread(start, pivot - 1), thread(pivot, end)]) (the promise-library's merge of the two promises to complete the work). Same idea really.

Re:Writing a Non-Blocking JavaScript Quicksort by mattLummus on Wednesday June 10, 2015 @11:04AM (#9692723)
I was also curious about the lack of promises