-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorting.go
78 lines (65 loc) · 1.7 KB
/
sorting.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
package main
import (
"sort"
"strings"
)
// By is the helper type used to sort entries.
type By func(e1, e2 *Entry) bool
// Sort creates an EntrySorter and sorts the entries.
func (by By) Sort(entries []*Entry) {
es := &entrySorter{
entries: entries,
by: by,
}
sort.Sort(es)
}
// EntrySorter is the structure that contains the entries to be sorted and the function
// used to sort them.
type entrySorter struct {
entries []*Entry
by func(e1, e2 *Entry) bool
}
// Len returns the length of a slice of entries.
func (s *entrySorter) Len() int {
return len(s.entries)
}
// Swap changes the position of two different entries in a slice.
func (s *entrySorter) Swap(i, j int) {
s.entries[i], s.entries[j] = s.entries[j], s.entries[i]
}
// Less returns if an entry is lesser than another entry.
func (s *entrySorter) Less(i, j int) bool {
return s.by(s.entries[i], s.entries[j])
}
// Sorting function used to sort entries by title.
func titleSortFunc(e1, e2 *Entry) bool {
s1 := e1.Title
if e1.TitleSort != "" {
s1 = e1.TitleSort
}
s2 := e2.Title
if e2.TitleSort != "" {
s2 = e2.TitleSort
}
if strings.ToLower(s1) == strings.ToLower(s2) {
return e1.Year < e2.Year
} else {
return strings.ToLower(s1) < strings.ToLower(s2)
}
}
// Sorting function used to sort entries by year.
func yearSortFunc(e1, e2 *Entry) bool {
if e1.Year == e2.Year {
return strings.ToLower(e1.Title) < strings.ToLower(e2.Title)
} else {
return e1.Year < e2.Year
}
}
// Sorting function used to sort entries by rating.
func ratingSortFunc(e1, e2 *Entry) bool {
return e1.Rating > e2.Rating
}
// Sorting function used to sort entries by info field.
func infoSortFunc(e1, e2 *Entry) bool {
return e1.Info < e2.Info
}