1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00

sort map move to generics

This commit is contained in:
2022-04-22 17:17:02 +08:00
parent e06c8e3463
commit 5f6130ae58
3 changed files with 133 additions and 2 deletions

View File

@ -13,8 +13,8 @@ import (
func TestConcurrentMap(t *testing.T) { func TestConcurrentMap(t *testing.T) {
t.Log(runtime.GOMAXPROCS(runtime.NumCPU())) t.Log(runtime.GOMAXPROCS(runtime.NumCPU()))
key := "abc" key := "aaabc"
value := "bcd" value := "aabcd"
m := generics.NewConcurrnetMap[string, string]() m := generics.NewConcurrnetMap[string, string]()
m.Set(key, value) m.Set(key, value)

View File

@ -0,0 +1,86 @@
package generics
import (
"fmt"
"sort"
"strings"
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
)
type mapSorter[K constraints.Ordered, V any] struct {
keys []K
m map[K]V
}
func NewSortMap[K constraints.Ordered, V any](m map[K]V) *mapSorter[K, V] {
return &mapSorter[K, V]{
m: m,
keys: keys(m),
}
}
func (s *mapSorter[K, V]) Asc() *mapSorter[K, V] {
keys := s.keys
slices.Sort(keys)
return &mapSorter[K, V]{
m: s.m,
keys: keys,
}
}
func (s *mapSorter[K, V]) Desc() *mapSorter[K, V] {
keys := s.keys
// slices.SortFunc(keys, func(a, b E) bool {
// return a > b
// })
sort.Slice(keys, func(i, j int) bool {
return keys[i] > keys[j]
})
return &mapSorter[K, V]{
m: s.m,
keys: keys,
}
}
func (s *mapSorter[K, V]) Join(sep string, f func(k K, v V) 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[K, V]) Keys() []K {
return s.keys
}
func (s *mapSorter[K, V]) Values() []V {
ret := make([]V, 0, len(s.m))
for _, k := range s.keys {
ret = append(ret, s.m[k])
}
return ret
}
func (s *mapSorter[K, V]) String() string {
return fmt.Sprintf("map[%s]", s.Join(" ", func(k K, v V) string {
return fmt.Sprintf("%v:%v", k, v)
}))
}
func keys[K comparable, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}

View File

@ -0,0 +1,45 @@
package generics
import (
"fmt"
"testing"
)
func TestSort(t *testing.T) {
m := map[string]any{
"Bcd": "bcd",
"Abc": "abc",
}
t.Log(NewSortMap(m).Values())
t.Log(NewSortMap(m).Desc().Values())
t.Log(NewSortMap(m).Asc().Values())
}
func TestMapSortInt(t *testing.T) {
m := map[string]int{
"Bcd": 8,
"Abc": 4,
}
ret := NewSortMap(m).Desc().Values()
t.Log(NewSortMap(m).Desc())
t.Log(NewSortMap(m).Asc())
t.Log(ret)
}
func TestJoin(t *testing.T) {
m := map[string]any{
"Bcd": "bcd",
"Abc": "abc",
"Efg": "efg",
}
t.Log(m)
j := NewSortMap(m).Asc().Join("&", func(k string, v any) string {
return fmt.Sprintf("%s=%v", k, v)
})
t.Log(j)
}