forked from eaciit/crowd
/
sorter.go
60 lines (48 loc) · 1.06 KB
/
sorter.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
package crowd
import (
"errors"
"sort"
"github.com/eaciit/toolkit"
)
type SortDirection string
const (
SortAscending SortDirection = "asc"
SortDescending SortDirection = "desc"
)
type Sorter struct {
SliceBase
FnSort FnCrowd
Direction SortDirection
}
func NewSorter(data interface{}, fnsort FnCrowd) (s *Sorter, e error) {
if !toolkit.IsPointer(data) || !toolkit.IsSlice(data) {
e = errors.New("crowd.NewSorter: data is not pointer of slice")
return
}
s = new(Sorter)
s.data = data
s.FnSort = _fn(fnsort)
return
}
func (s *Sorter) Swap(i, j int) {
//s.data[i], s.data[j] = s.data[j], s.data[i
//toolkit.Printf("Swapping: %d and %d \n", i, j)
si := s.Item(i)
sj := s.Item(j)
s.Set(i, sj)
s.Set(j, si)
}
func (s *Sorter) Less(i, j int) bool {
v0 := s.FnSort(s.Item(i))
v1 := s.FnSort(s.Item(j))
if s.Direction == SortAscending {
return toolkit.Compare(v0, v1, "$lt")
} else {
return toolkit.Compare(v0, v1, "$gt")
}
}
func (s *Sorter) Sort(direction SortDirection) interface{} {
s.Direction = direction
sort.Sort(s)
return s.data
}