通用包
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

51 lines
769 B

2 years ago
package set
2 years ago
type Set[T comparable] map[T]struct{}
1 year ago
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
}
2 years ago
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
}