go-study/map_set/map.go
2024-01-25 14:49:50 +08:00

37 lines
695 B
Go

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
}