-
Notifications
You must be signed in to change notification settings - Fork 2
/
intersort.go
36 lines (31 loc) · 1.07 KB
/
intersort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package intersort // import "lukechampine.com/intersort"
import (
"fmt"
"reflect"
"sort"
)
func less(x, y interface{}) bool {
justX := fmt.Sprint(map[interface{}]struct{}{x: struct{}{}})
justY := fmt.Sprint(map[interface{}]struct{}{y: struct{}{}})
return fmt.Sprint(map[interface{}]struct{}{
x: struct{}{},
y: struct{}{},
}) == fmt.Sprintf("map[%v %v]", justX[4:len(justX)-1], justY[4:len(justY)-1])
}
// Slice implements sort.Interface for arbitrary objects, according to the map
// ordering of the fmt package.
type Slice []interface{}
func (is Slice) Len() int { return len(is) }
func (is Slice) Swap(i, j int) { is[i], is[j] = is[j], is[i] }
func (is Slice) Less(i, j int) bool { return less(is[i], is[j]) }
// Sort sorts arbitrary objects according to the map ordering of the fmt
// package.
func Sort(slice interface{}) {
val := reflect.ValueOf(slice)
if val.Type().Kind() != reflect.Slice {
panic("intersort: cannot sort non-slice type")
}
sort.Slice(slice, func(i, j int) bool {
return less(val.Index(i).Interface(), val.Index(j).Interface())
})
}