| 1 |
package set |
| 2 |
|
| 3 |
import "github.com/jesseduffield/generics/maps" |
| 4 |
|
| 5 |
type Set[T comparable] struct { |
| 6 |
hashMap map[T]bool |
| 7 |
} |
| 8 |
|
| 9 |
func New[T comparable]() *Set[T] { |
| 10 |
return &Set[T]{hashMap: make(map[T]bool)} |
| 11 |
} |
| 12 |
|
| 13 |
func NewFromSlice[T comparable](slice []T) *Set[T] { |
| 14 |
result := &Set[T]{hashMap: make(map[T]bool, len(slice))} |
| 15 |
result.Add(slice...) |
| 16 |
return result |
| 17 |
} |
| 18 |
|
| 19 |
func (s *Set[T]) Add(values ...T) { |
| 20 |
for _, value := range values { |
| 21 |
s.hashMap[value] = true |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
func (s *Set[T]) Remove(value T) { |
| 26 |
delete(s.hashMap, value) |
| 27 |
} |
| 28 |
|
| 29 |
func (s *Set[T]) RemoveSlice(slice []T) { |
| 30 |
for _, value := range slice { |
| 31 |
s.Remove(value) |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
func (s *Set[T]) Includes(value T) bool { |
| 36 |
return s.hashMap[value] |
| 37 |
} |
| 38 |
|
| 39 |
func (s *Set[T]) Len() int { |
| 40 |
return len(s.hashMap) |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
func (s *Set[T]) ToSlice() []T { |
| 45 |
return maps.Keys(s.hashMap) |
| 46 |
} |