47 lines
864 B
Go
47 lines
864 B
Go
package generics
|
|
|
|
type Set[T comparable] map[T]struct{}
|
|
|
|
// New produces a new set containing the given values.
|
|
func NewSet[T comparable](vals ...T) Set[T] {
|
|
s := Set[T](make(map[T]struct{}))
|
|
for _, val := range vals {
|
|
s.Add(val)
|
|
}
|
|
return Set[T](s)
|
|
}
|
|
|
|
// Add adds values to the set.
|
|
func (s Set[T]) Add(vals ...T) {
|
|
for _, val := range vals {
|
|
s[val] = struct{}{}
|
|
}
|
|
}
|
|
|
|
// Check if a value is already present in the set.
|
|
func (s Set[T]) Has(val T) bool {
|
|
_, ok := s[val]
|
|
return ok
|
|
}
|
|
|
|
// Removes a value from the set.
|
|
func (s Set[T]) Remove(vals ...T) {
|
|
for _, val := range vals {
|
|
delete(s, val)
|
|
}
|
|
}
|
|
|
|
// Number of values in the set.
|
|
func (s Set[T]) Length() int {
|
|
return len(s)
|
|
}
|
|
|
|
// Get a slice of values in the set.
|
|
func (s Set[T]) Values() []T {
|
|
values := make([]T, 0, len(s))
|
|
for k := range s {
|
|
values = append(values, k)
|
|
}
|
|
return values
|
|
}
|