Source file
src/sort/example_multi_test.go
Documentation: sort
1
2
3
4
5 package sort_test
6
7 import (
8 "fmt"
9 "sort"
10 )
11
12
13 type Change struct {
14 user string
15 language string
16 lines int
17 }
18
19 type lessFunc func(p1, p2 *Change) bool
20
21
22 type multiSorter struct {
23 changes []Change
24 less []lessFunc
25 }
26
27
28 func (ms *multiSorter) Sort(changes []Change) {
29 ms.changes = changes
30 sort.Sort(ms)
31 }
32
33
34
35 func OrderedBy(less ...lessFunc) *multiSorter {
36 return &multiSorter{
37 less: less,
38 }
39 }
40
41
42 func (ms *multiSorter) Len() int {
43 return len(ms.changes)
44 }
45
46
47 func (ms *multiSorter) Swap(i, j int) {
48 ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
49 }
50
51
52
53
54
55
56
57 func (ms *multiSorter) Less(i, j int) bool {
58 p, q := &ms.changes[i], &ms.changes[j]
59
60 var k int
61 for k = 0; k < len(ms.less)-1; k++ {
62 less := ms.less[k]
63 switch {
64 case less(p, q):
65
66 return true
67 case less(q, p):
68
69 return false
70 }
71
72 }
73
74
75 return ms.less[k](p, q)
76 }
77
78 var changes = []Change{
79 {"gri", "Go", 100},
80 {"ken", "C", 150},
81 {"glenda", "Go", 200},
82 {"rsc", "Go", 200},
83 {"r", "Go", 100},
84 {"ken", "Go", 200},
85 {"dmr", "C", 100},
86 {"r", "C", 150},
87 {"gri", "Smalltalk", 80},
88 }
89
90
91
92
93 func Example_sortMultiKeys() {
94
95 user := func(c1, c2 *Change) bool {
96 return c1.user < c2.user
97 }
98 language := func(c1, c2 *Change) bool {
99 return c1.language < c2.language
100 }
101 increasingLines := func(c1, c2 *Change) bool {
102 return c1.lines < c2.lines
103 }
104 decreasingLines := func(c1, c2 *Change) bool {
105 return c1.lines > c2.lines
106 }
107
108
109 OrderedBy(user).Sort(changes)
110 fmt.Println("By user:", changes)
111
112
113 OrderedBy(user, increasingLines).Sort(changes)
114 fmt.Println("By user,<lines:", changes)
115
116 OrderedBy(user, decreasingLines).Sort(changes)
117 fmt.Println("By user,>lines:", changes)
118
119 OrderedBy(language, increasingLines).Sort(changes)
120 fmt.Println("By language,<lines:", changes)
121
122 OrderedBy(language, increasingLines, user).Sort(changes)
123 fmt.Println("By language,<lines,user:", changes)
124
125
126
127
128
129
130
131
132 }
133
View as plain text