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

93 lines
1.4 KiB

2 years ago
package set
2 years ago
11 months ago
import "sort"
2 years ago
11 months ago
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] {
2 years ago
return make(map[T]struct{})
}
11 months ago
func NewSetWithItems[T Comparable](items ...T) Set[T] {
2 years ago
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
}
11 months ago
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
}