-
Notifications
You must be signed in to change notification settings - Fork 12
/
sort.go
70 lines (57 loc) · 1.02 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
package datatable
import (
"sort"
"github.com/datasweet/datatable/serie"
)
// SortBy defines a sort to be applied
type SortBy struct {
Column string
Desc bool
index int
}
// credits : https://stackoverflow.com/questions/36122668/how-to-sort-struct-with-multiple-sort-parameters
type sorter struct {
t *DataTable
by []SortBy
}
func (s *sorter) Len() int {
return s.t.nrows
}
func (s *sorter) Swap(i, j int) {
s.t.SwapRow(i, j)
}
func (s *sorter) Less(i, j int) bool {
for _, by := range s.by {
sr := s.t.cols[by.index].serie
switch cmp := sr.Compare(i, j); cmp {
case serie.Eq:
continue
case serie.Gt:
return by.Desc
case serie.Lt:
return !by.Desc
}
}
return false
}
// Sort the table
func (t *DataTable) Sort(by ...SortBy) *DataTable {
cpy := t.Copy()
if len(by) == 0 {
return cpy
}
for i := range by {
b := &by[i]
// Check if column exists
b.index = t.ColumnIndex(b.Column)
if b.index < 0 {
return cpy
}
}
srt := &sorter{
t: cpy,
by: by,
}
sort.Sort(srt)
return cpy
}