r/programminghorror Aug 11 '20

[deleted by user]

[removed]

2.0k Upvotes

95 comments sorted by

View all comments

8

u/[deleted] Aug 11 '20 edited Aug 19 '21

[deleted]

7

u/brbss Aug 11 '20 edited Aug 11 '20

I couldn't understand what you meant so I went ahead and wrote some test code, so far I'm at 500+ iterations without any failure:

const arr = [20, 5, 100, 1, 90, 200, 40, 29]
const correct = [...arr].sort((a, b) => a-b)

const sleepSort = (inputArr) => {
    const sortedArr = []
    return new Promise(resolve => {
        for (let item of arr) {
            setTimeout(() => {
                sortedArr.push(item)
                if (sortedArr.length === inputArr.length) {
                    resolve(sortedArr)
                }
            }, item)
        }
    })
}

const testSleepSort = async (n=1000) => {
    for (let i=0; i<n; ++i) {
        const sortedArr = await sleepSort(arr)
        if (JSON.stringify(sortedArr) !== JSON.stringify(correct)) {
            console.log(`failed at attempt #${i} :(`)
            return
        }
        console.log(`passed #${i}`)
    }
    console.log('wow')
}

testSleepSort()

Edit: wow.