-
Notifications
You must be signed in to change notification settings - Fork 14
/
sort.go
91 lines (79 loc) · 1.51 KB
/
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
package goql
import (
"strings"
"github.com/fzerorubigd/goql/parse"
)
// sortMe is a type to order data based on order sql statement.
type sortMe struct {
order parse.Orders
data [][]Getter
}
func (s *sortMe) Len() int {
return len(s.data)
}
func compareTypes(i, j interface{}, lesser, greater, equal int) int {
// i, j are not nil
switch i.(type) {
case bool:
if i.(bool) == j.(bool) {
return equal
}
if i.(bool) {
return lesser
}
return greater
case float64:
if i.(float64) == j.(float64) {
return equal
}
if i.(float64) < j.(float64) {
return lesser
}
return greater
case string:
if i.(string) == j.(string) {
return equal
}
i := strings.Compare(strings.ToLower(i.(string)), strings.ToLower(j.(string)))
if i < 0 {
return lesser
}
return greater
}
return equal
}
func interfaceLess(i, j interface{}, desc bool) int {
lesser := 1
greater := -1
equal := 0
if desc {
lesser = -1
greater = 1
}
if i == nil && j != nil {
return lesser
}
if i != nil && j == nil {
return greater
}
if i == nil && j == nil {
return equal
}
return compareTypes(i, j, lesser, greater, equal)
}
func (s *sortMe) Less(i int, j int) bool {
ii := s.data[i]
ij := s.data[j]
for o := range s.order {
res := interfaceLess(ii[s.order[o].Index].Get(), ij[s.order[o].Index].Get(), s.order[o].DESC)
if res < 0 {
return false
} else if res > 0 {
return true
}
}
return false
}
func (s *sortMe) Swap(i int, j int) {
s.data[i], s.data[j] = s.data[j], s.data[i]
}