mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 00:22:41 +08:00
map join
This commit is contained in:
17
maps/map.go
17
maps/map.go
@ -1,6 +1,10 @@
|
||||
package maps
|
||||
|
||||
import "golang.org/x/exp/constraints"
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
type Map[K constraints.Ordered, V any] interface {
|
||||
Set(key K, value V) // 设置值
|
||||
@ -32,3 +36,14 @@ func Merge[K comparable, V any](mm ...map[K]V) map[K]V {
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// 按照键值生成字符串
|
||||
func Join[K constraints.Ordered, V any](m Map[K, V], sep string, f func(k K, v V) string) string {
|
||||
slice := make([]string, 0, m.Count())
|
||||
for _, k := range m.Keys() {
|
||||
v, _ := m.Get(k)
|
||||
slice = append(slice, f(k, v))
|
||||
}
|
||||
|
||||
return strings.Join(slice, sep)
|
||||
}
|
||||
|
@ -2,7 +2,6 @@ package maps
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
"golang.org/x/exp/slices"
|
||||
@ -32,7 +31,6 @@ func NewSortedMap[K constraints.Ordered, V any](maps ...map[K]V) *sorted_map[K,
|
||||
}
|
||||
|
||||
func NewSortedByMap[K constraints.Ordered, V any](m Map[K, V]) *sorted_map[K, V] {
|
||||
|
||||
return &sorted_map[K, V]{maps: m, keys: m.Keys()}
|
||||
}
|
||||
|
||||
@ -94,16 +92,6 @@ func (m *sorted_map[K, V]) Exist(key K) bool {
|
||||
return m.Exist(key)
|
||||
}
|
||||
|
||||
func (m *sorted_map[K, V]) Join(sep string, f func(k K, v V) string) string {
|
||||
slice := make([]string, 0, m.maps.Count())
|
||||
for _, k := range m.keys {
|
||||
v, _ := m.maps.Get(k)
|
||||
slice = append(slice, f(k, v))
|
||||
}
|
||||
|
||||
return strings.Join(slice, sep)
|
||||
}
|
||||
|
||||
func (m *sorted_map[K, V]) Keys() []K {
|
||||
return m.keys
|
||||
}
|
||||
@ -123,7 +111,7 @@ func (s *sorted_map[K, V]) ToMap() map[K]V {
|
||||
}
|
||||
|
||||
func (m *sorted_map[K, V]) String() string {
|
||||
return fmt.Sprintf("map[%s]", m.Join(" ", func(k K, v V) string {
|
||||
return fmt.Sprintf("map[%s]", Join[K, V](m, " ", func(k K, v V) string {
|
||||
return fmt.Sprintf("%v:%v", k, v)
|
||||
}))
|
||||
}
|
||||
|
Reference in New Issue
Block a user