/
mapsort.go
49 lines (39 loc) · 861 Bytes
/
mapsort.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
package utility
import (
"sort"
"strings"
)
type MapSorter struct {
OrderBy string
Items []MapItem
}
type MapItem struct {
Key string
Val interface{}
}
func NewMapSorter(m map[string]interface{}, o string) MapSorter {
ms := MapSorter{}
ms.OrderBy = o
for k, v := range m {
ms.Items = append(ms.Items, MapItem{k, v})
}
return ms
}
func (ms MapSorter) Len() int {
return len(ms.Items)
}
//按键排序
func (ms MapSorter) Less(i, j int) bool {
if ms.OrderBy == "asc" {
return strings.Compare(ms.Items[i].Key, ms.Items[j].Key) <= 0
}
return strings.Compare(ms.Items[i].Key, ms.Items[j].Key) > 0
}
func (ms MapSorter) Swap(i, j int) {
ms.Items[i], ms.Items[j] = ms.Items[j], ms.Items[i]
}
func MapSortByKey(list map[string]interface{}, orderBy string) []MapItem {
ms := NewMapSorter(list, orderBy)
sort.Sort(ms)
return ms.Items
}