-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathless.go
40 lines (33 loc) · 1.18 KB
/
less.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
package permutation
import (
"errors"
"reflect"
)
// Less defines the comparison function that can be used to sort a list
type Less func(left, right interface{}) bool
func getLessFunctionByValueType(value reflect.Value) (Less, error) {
switch value.Type().Elem().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return lessInt, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return lessUint, nil
case reflect.Float32, reflect.Float64:
return lessFloat, nil
case reflect.String:
return lessString, nil
default:
return nil, errors.New("the element type of slice is not ordered, you must provide a function")
}
}
func lessUint(left, right interface{}) bool {
return reflect.ValueOf(left).Uint() < reflect.ValueOf(right).Uint()
}
func lessInt(left, right interface{}) bool {
return reflect.ValueOf(left).Int() < reflect.ValueOf(right).Int()
}
func lessFloat(left, right interface{}) bool {
return reflect.ValueOf(left).Float() < reflect.ValueOf(right).Float()
}
func lessString(left, right interface{}) bool {
return reflect.ValueOf(left).Interface().(string) < reflect.ValueOf(right).Interface().(string)
}