mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 08:32:40 +08:00
sort map
This commit is contained in:
69
sort/sort.go
Normal file
69
sort/sort.go
Normal file
@ -0,0 +1,69 @@
|
||||
package sort
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type mapSorter[T any] struct {
|
||||
keys []string
|
||||
m map[string]T
|
||||
}
|
||||
|
||||
func SortByKey[T any](m map[string]T) *mapSorter[T] {
|
||||
return &mapSorter[T]{
|
||||
m: m,
|
||||
keys: keys(m),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *mapSorter[T]) Asc() *mapSorter[T] {
|
||||
keys := s.keys
|
||||
sort.Strings(keys)
|
||||
|
||||
return &mapSorter[T]{
|
||||
m: s.m,
|
||||
keys: keys,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *mapSorter[T]) Desc() *mapSorter[T] {
|
||||
keys := s.keys
|
||||
sort.Sort(sort.Reverse(sort.StringSlice(keys)))
|
||||
|
||||
return &mapSorter[T]{
|
||||
m: s.m,
|
||||
keys: keys,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *mapSorter[T]) Join(sep string, f func(k string, v T) string) string {
|
||||
slice := make([]string, 0, len(s.m))
|
||||
for _, k := range s.keys {
|
||||
slice = append(slice, f(k, s.m[k]))
|
||||
}
|
||||
|
||||
return strings.Join(slice, sep)
|
||||
}
|
||||
|
||||
func (s *mapSorter[T]) Keys() []string {
|
||||
return s.keys
|
||||
}
|
||||
|
||||
func (s *mapSorter[T]) Values() []T {
|
||||
ret := make([]T, 0, len(s.m))
|
||||
for _, k := range s.keys {
|
||||
ret = append(ret, s.m[k])
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func keys[T any](m map[string]T) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
42
sort/sort_test.go
Normal file
42
sort/sort_test.go
Normal file
@ -0,0 +1,42 @@
|
||||
package sort
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
m := map[string]any{
|
||||
"Bcd": "bcd",
|
||||
"Abc": "abc",
|
||||
}
|
||||
|
||||
t.Log(SortByKey(m).Values())
|
||||
t.Log(SortByKey(m).Desc().Values())
|
||||
t.Log(SortByKey(m).Asc().Values())
|
||||
}
|
||||
|
||||
func TestMapSortInt(t *testing.T) {
|
||||
m := map[string]int{
|
||||
"Bcd": 8,
|
||||
"Abc": 4,
|
||||
}
|
||||
|
||||
ret := SortByKey(m).Desc().Values()
|
||||
|
||||
t.Log(ret)
|
||||
}
|
||||
|
||||
func TestJoin(t *testing.T) {
|
||||
m := map[string]any{
|
||||
"Bcd": "bcd",
|
||||
"Abc": "abc",
|
||||
"Efg": "efg",
|
||||
}
|
||||
|
||||
j := SortByKey(m).Asc().Join("&", func(k string, v any) string {
|
||||
return fmt.Sprintf("%s=%v", k, v)
|
||||
})
|
||||
|
||||
t.Log(j)
|
||||
}
|
Reference in New Issue
Block a user