通用包
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
utils/pkg/set/set.go

92 lines
1.4 KiB

package set
import "sort"
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Float interface {
~float32 | ~float64
}
type String interface {
~string
}
type Comparable interface {
Integer | Float | String
}
type Set[T Comparable] map[T]struct{}
func NewSet[T Comparable]() Set[T] {
return make(map[T]struct{})
}
func NewSetWithItems[T Comparable](items ...T) Set[T] {
s := make(Set[T])
s.AddWithOutEmpty(items...)
return s
}
func (s Set[T]) Add(items ...T) {
for _, v := range items {
s[v] = struct{}{}
}
}
func (s Set[T]) AddWithOutEmpty(items ...T) {
var empty T
for _, v := range items {
if v == empty {
continue
}
s[v] = struct{}{}
}
}
func (s Set[T]) Has(data T) bool {
_, ok := s[data]
return ok
}
func (s Set[T]) Delete(data T) {
delete(s, data)
}
func (s Set[T]) Count() int32 {
return int32(len(s))
}
func (s Set[T]) ToSlice() []T {
res := make([]T, 0, len(s))
for k := range s {
res = append(res, k)
}
return res
}
func (s Set[T]) ToSortSlice() []T {
res := make([]T, 0, len(s))
for k := range s {
res = append(res, k)
}
sort.Slice(res, func(i, j int) bool {
return res[i] < res[j]
})
return res
}
func (s Set[T]) ToCustomSortSlice(f func(i, j int) bool) []T {
res := make([]T, 0, len(s))
for k := range s {
res = append(res, k)
}
sort.Slice(res, func(i, j int) bool {
return f(i, j)
})
return res
}