增加map集合示例

This commit is contained in:
wangwenbin 2024-01-25 14:49:50 +08:00
parent 9fce7acead
commit b6979d0594
2 changed files with 52 additions and 0 deletions

36
map_set/map.go Normal file
View File

@ -0,0 +1,36 @@
package map_set
import (
"sort"
"golang.org/x/exp/constraints"
)
func New[T comparable](slice ...T) map[T]struct{} {
mapSet := make(map[T]struct{}, len(slice))
for _, element := range slice {
mapSet[element] = struct{}{}
}
return mapSet
}
func In[T comparable](needle T, haystack map[T]struct{}) bool {
_, exists := haystack[needle]
return exists
}
func Keys[T comparable](mapSet map[T]struct{}) []T {
slice := make([]T, 0, len(mapSet))
for k := range mapSet {
slice = append(slice, k)
}
return slice
}
func Sort[T constraints.Ordered](mapSet map[T]struct{}) []T {
keys := Keys(mapSet)
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
return keys
}

16
map_set/map_test.go Normal file
View File

@ -0,0 +1,16 @@
package map_set
import "testing"
func TestMapSet(t *testing.T) {
mapSet := New(2, 3, 1, 5, 4)
res := In(3, mapSet)
if !res {
t.Error("In() error")
}
slice := Sort(mapSet)
if slice[0] != 1 || slice[1] != 2 || slice[2] != 3 || slice[3] != 4 || slice[4] != 5 {
t.Error("Sort() error")
}
}