-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslice_sort.go
217 lines (189 loc) · 6.95 KB
/
slice_sort.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package tricks
import (
"math"
"reflect"
"sort"
)
func swapValue(v reflect.Value, i, j int) {
vi := v.Index(i)
vii := reflect.ValueOf(vi.Interface())
vj := v.Index(j)
vi.Set(vj)
vj.Set(vii)
}
// Reverse reverses the order of elements of the slice in place.
func (ts TrickSlice) Reverse() TrickSlice {
v := reflect.Value(ts)
for i, j := 0, v.Len()-1; i < j; i, j = i+1, j-1 {
swapValue(v, i, j)
}
return ts
}
// Multiple types of sortable reflect.Values so that we can have independant
// Less() implementations, rather than one big switch statement inside Less().
type sortableInts reflect.Value
type sortableFloats reflect.Value
type sortableStrings reflect.Value
type sortableIface reflect.Value
func (p sortableInts) Len() int { return reflect.Value(p).Len() }
func (p sortableFloats) Len() int { return reflect.Value(p).Len() }
func (p sortableStrings) Len() int { return reflect.Value(p).Len() }
func (p sortableIface) Len() int {
f := reflect.Value(p).MethodByName("Len")
return f.Call(nil)[0].Interface().(int)
}
func (p sortableInts) Swap(i, j int) { swapValue(reflect.Value(p), i, j) }
func (p sortableFloats) Swap(i, j int) { swapValue(reflect.Value(p), i, j) }
func (p sortableStrings) Swap(i, j int) { swapValue(reflect.Value(p), i, j) }
func (p sortableIface) Swap(i, j int) {
f := reflect.Value(p).MethodByName("Swap")
args := []reflect.Value{reflect.ValueOf(i), reflect.ValueOf(j)}
f.Call(args)
}
func (p sortableInts) Less(i, j int) bool {
v := reflect.Value(p)
return v.Index(i).Int() < v.Index(j).Int()
}
func (p sortableFloats) Less(i, j int) bool {
v := reflect.Value(p)
vi := v.Index(i).Float()
vj := v.Index(j).Float()
return vi < vj || math.IsNaN(vi) && !math.IsNaN(vj)
}
func (p sortableStrings) Less(i, j int) bool {
v := reflect.Value(p)
return v.Index(i).String() < v.Index(j).String()
}
func (p sortableIface) Less(i, j int) bool {
f := reflect.Value(p).MethodByName("Less")
args := []reflect.Value{reflect.ValueOf(i), reflect.ValueOf(j)}
return f.Call(args)[0].Bool()
}
// We declare these types because we want to check that the slice is of this
// exact type, and not just having elements of the same reflect.Kind. In this
// way, we won't sort elements that look like ints, unless that slice type is
// either exactly []int or it explicitly implements sort.Interface.
var (
typeIntSlice = reflect.SliceOf(reflect.TypeOf((*int)(nil)).Elem()) // []int
typeInt8Slice = reflect.SliceOf(reflect.TypeOf((*int8)(nil)).Elem()) // []int8
typeInt16Slice = reflect.SliceOf(reflect.TypeOf((*int16)(nil)).Elem()) // []int16
typeInt32Slice = reflect.SliceOf(reflect.TypeOf((*int32)(nil)).Elem()) // []int32
typeInt64Slice = reflect.SliceOf(reflect.TypeOf((*int64)(nil)).Elem()) // []int64
typeStringSlice = reflect.SliceOf(reflect.TypeOf((*string)(nil)).Elem()) // []string
typeFloat32Slice = reflect.SliceOf(reflect.TypeOf((*float32)(nil)).Elem()) // []float32
typeFloat64Slice = reflect.SliceOf(reflect.TypeOf((*float64)(nil)).Elem()) // []float64
typeSortInterface = reflect.TypeOf((*sort.Interface)(nil)).Elem() // sort.Interface
)
func getSortable(context string, v reflect.Value) sort.Interface {
switch v.Type() {
case typeStringSlice:
return sortableStrings(v)
case typeIntSlice, typeInt8Slice, typeInt16Slice, typeInt32Slice, typeInt64Slice:
return sortableInts(v)
case typeFloat32Slice, typeFloat64Slice:
return sortableFloats(v)
default:
if v.Type().Implements(typeSortInterface) {
return sortableIface(v)
}
panic("tricks: " + context + ": slice doesn't implement sort.Interface")
}
}
// Sort the contents of the slice in place. Slices of type string, int, or float
// are handled automatically, otherwise, the underlying slice must implement
// sort.Interface or this method panics.
func (ts TrickSlice) Sort() TrickSlice {
v := reflect.Value(ts)
sort.Sort(getSortable("slice.Sort", v))
return ts
}
// Find the maximum value in O(n) time.
func findIndexMax(s sort.Interface) (max int) {
if s.Len() == 1 {
return
}
for i := 1; i < s.Len(); i++ {
if s.Less(max, i) {
max = i
}
}
return
}
func findIndexMin(s sort.Interface) int {
return findIndexMax(sort.Reverse(s))
}
// Max returns the element of the slice with the maximum value. Slices of type
// string, int, or float are handled automatically, otherwise, the underlying
// slice must implement sort.Interface or this method panics.
// If the slice is empty, this method returns the nil interface{}.
func (ts TrickSlice) Max() interface{} {
v := reflect.Value(ts)
if v.Len() == 0 {
return nil
}
return v.Index(findIndexMax(getSortable("slice.Max", v))).Interface()
}
// Min returns the element of the slice with the minimum value. Slices of type
// string, int, or float are handled automatically, otherwise, the underlying
// slice must implement sort.Interface or this method panics.
// If the slice is empty, this method returns the nil interface{}.
func (ts TrickSlice) Min() interface{} {
v := reflect.Value(ts)
if v.Len() == 0 {
return nil
}
return v.Index(findIndexMin(getSortable("slice.Min", v))).Interface()
}
type sortableBy struct {
val reflect.Value
sortFn interface{}
}
func (s *sortableBy) Len() int {
return s.val.Len()
}
func (s *sortableBy) Swap(i, j int) {
swapValue(s.val, i, j)
}
func (s *sortableBy) Less(i, j int) bool {
fn := reflect.ValueOf(s.sortFn)
return fn.Call([]reflect.Value{s.val.Index(i), s.val.Index(j)})[0].Bool()
}
func isValidSortByFunc(funcType, sliceType reflect.Type) bool {
return funcType.NumIn() == 2 && funcType.NumOut() == 1 &&
funcType.In(0) == sliceType.Elem() &&
funcType.In(1) == sliceType.Elem() &&
funcType.Out(0).Kind() == reflect.Bool
}
// SortBy sorts the slice by some comparison `func(a, b T) bool` that returns
// whether element `a < b`.
func (ts TrickSlice) SortBy(fn interface{}) TrickSlice {
v := reflect.Value(ts)
f := reflect.ValueOf(fn)
if !f.IsValid() || !isValidSortByFunc(f.Type(), v.Type()) {
panic("tricks: slice.SortBy: invalid function type")
}
sort.Sort(&sortableBy{v, fn})
return ts
}
// MinBy returns the element with the minimum value by some comparison
// `func(a, b T) bool` that returns whether element `a < b`.
// If the slice is empty, this method returns the nil interface{}.
func (ts TrickSlice) MinBy(fn interface{}) interface{} {
v := reflect.Value(ts)
f := reflect.ValueOf(fn)
if !f.IsValid() || !isValidSortByFunc(f.Type(), v.Type()) {
panic("tricks: slice.MinBy: invalid function type")
}
return v.Index(findIndexMin(&sortableBy{v, fn})).Interface()
}
// MaxBy returns the element with the maximum value by some comparison
// `func(a, b T) bool` that returns whether element `a < b`.
// If the slice is empty, this method returns the nil interface{}.
func (ts TrickSlice) MaxBy(fn interface{}) interface{} {
v := reflect.Value(ts)
f := reflect.ValueOf(fn)
if !f.IsValid() || !isValidSortByFunc(f.Type(), v.Type()) {
panic("tricks: slice.MaxBy: invalid function type")
}
return v.Index(findIndexMax(&sortableBy{v, fn})).Interface()
}