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:
@ -2,7 +2,6 @@ package generics
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"golang.org/x/exp/constraints"
|
"golang.org/x/exp/constraints"
|
||||||
@ -21,6 +20,32 @@ func NewSortMap[K constraints.Ordered, V any](m map[K]V) *mapSorter[K, V] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *mapSorter[K, V]) Set(key K, value V) {
|
||||||
|
s.m[key] = value
|
||||||
|
s.keys = append(s.keys, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *mapSorter[K, V]) Get(key K) (V, bool) {
|
||||||
|
v, ok := s.m[key]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *mapSorter[K, V]) Delete(key K) {
|
||||||
|
delete(s.m, key)
|
||||||
|
|
||||||
|
keys := keys(s.m)
|
||||||
|
s.keys = keys
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *mapSorter[K, V]) Clear() {
|
||||||
|
s.m = map[K]V{}
|
||||||
|
s.keys = []K{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *mapSorter[K, V]) Count() int {
|
||||||
|
return len(s.m)
|
||||||
|
}
|
||||||
|
|
||||||
func (s *mapSorter[K, V]) Asc() *mapSorter[K, V] {
|
func (s *mapSorter[K, V]) Asc() *mapSorter[K, V] {
|
||||||
keys := s.keys
|
keys := s.keys
|
||||||
slices.Sort(keys)
|
slices.Sort(keys)
|
||||||
@ -34,12 +59,8 @@ func (s *mapSorter[K, V]) Asc() *mapSorter[K, V] {
|
|||||||
func (s *mapSorter[K, V]) Desc() *mapSorter[K, V] {
|
func (s *mapSorter[K, V]) Desc() *mapSorter[K, V] {
|
||||||
keys := s.keys
|
keys := s.keys
|
||||||
|
|
||||||
// slices.SortFunc(keys, func(a, b E) bool {
|
slices.SortFunc(keys, func(a, b K) bool {
|
||||||
// return a > b
|
return a > b
|
||||||
// })
|
|
||||||
|
|
||||||
sort.Slice(keys, func(i, j int) bool {
|
|
||||||
return keys[i] > keys[j]
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return &mapSorter[K, V]{
|
return &mapSorter[K, V]{
|
||||||
|
Reference in New Issue
Block a user