Sleep Sort
Written 2 weeks ago
Behold
const arr = [1, 5, 9, 7, 2, 8, 4, 3, 6]
arr.forEach((x) => setTimeout(() => console.log(x), x * 1000))
// Output: 1, 2, 3, 4, 5, 6, 7, 8, 9
Try it yourself, open a browser console window and paste this code!
What sorcery is this?
Time: 0s
1
5
9
7
2
8
4
3
6
More resources for the curious
Bonus Example
Here’s a go
code example, just for kicks:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
arr := []int{1, 5, 9, 7, 2, 8, 4, 3, 6}
for _, n := range arr {
wg.Add(1)
go (func() {
time.Sleep(time.Duration(n) * time.Second)
fmt.Println(n)
wg.Done()
})()
}
wg.Wait()
fmt.Println("Voila!")
}
and another in bash
, probably where “sleep” originated:
#!/usr/bin/env bash
arr=(1 5 9 7 2 8 4 3 6)
for i in ${arr[*]}; do
sleep $i && echo $i &
done
wait
echo "Voila!"