crazy4groovy
10/31/2017 - 1:50 PM

sleep sort (https://dev.to/sishaarrao/sleep-sort-where-theory-meets-sobering-reality-b3m)

function sleepSort(array/* : int[] */, cb) {
    var result = []
    array.forEach(i => {
        setTimeout(() => {
            result.push(i)
            if (result.length === array.length) cb(result)
        }, i * 1000) // it doesn't need to sleep this long, but it's consistent with bash version
    })
}
function sleepSortFast(array/* : float[] */, cb) {
    var maxDigits = array.reduce((result, i) => {
      var digits = (('' + i).match(/\d+\.?(\d*)$/) || [null, ''])[1].length
      return Math.max(result, digits)
    }, 0)
    var delayFactorMs = (Math.pow(10, maxDigits)) // how long we have to wait
    var result = []
    array.forEach(i => {
        setTimeout(() => {
            result.push(i)
            if (result.length === array.length) cb(result)
        }, (i * delayFactorMs) + (i * 10)) // a bit of buffer time
    })
}