2025-05-06 22:58:18 -04:00
|
|
|
package simpleset
|
|
|
|
|
|
|
|
type SimpleSet[T comparable] struct {
|
|
|
|
set map[T]any
|
|
|
|
}
|
|
|
|
|
|
|
|
func New[T comparable]() *SimpleSet[T] {
|
|
|
|
return &SimpleSet[T]{
|
|
|
|
set: make(map[T]any),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SimpleSet[T]) lockedInitMapIfNil() {
|
|
|
|
if s.set == nil {
|
|
|
|
s.set = make(map[T]any)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SimpleSet[T]) Insert(t T) (inserted bool) {
|
|
|
|
s.lockedInitMapIfNil()
|
|
|
|
if _, found := s.set[t]; found {
|
|
|
|
return false
|
|
|
|
} else {
|
|
|
|
s.set[t] = struct{}{}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-05-25 17:30:53 -04:00
|
|
|
func (s *SimpleSet[T]) InsertSlice(slice []T) (inserted []bool) {
|
|
|
|
inserted = make([]bool, 0, len(slice))
|
|
|
|
for _, t := range slice {
|
|
|
|
inserted = append(inserted, s.Insert(t))
|
|
|
|
}
|
|
|
|
return inserted
|
|
|
|
}
|
|
|
|
|
2025-05-06 22:58:18 -04:00
|
|
|
func (s *SimpleSet[T]) Contains(t T) bool {
|
|
|
|
s.lockedInitMapIfNil()
|
|
|
|
_, found := s.set[t]
|
|
|
|
return found
|
|
|
|
}
|
|
|
|
|
2025-05-25 17:30:53 -04:00
|
|
|
func (s *SimpleSet[T]) ContainsSlice(slice []T) []bool {
|
|
|
|
results := make([]bool, 0, len(slice))
|
|
|
|
for _, t := range slice {
|
|
|
|
results = append(results, s.Contains(t))
|
|
|
|
}
|
|
|
|
return results
|
|
|
|
}
|
|
|
|
|
2025-05-06 22:58:18 -04:00
|
|
|
func (s *SimpleSet[T]) Len() int {
|
|
|
|
s.lockedInitMapIfNil()
|
|
|
|
return len(s.set)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SimpleSet[T]) ToSlice() []T {
|
|
|
|
s.lockedInitMapIfNil()
|
|
|
|
results := make([]T, 0, s.Len())
|
|
|
|
for k := range s.set {
|
|
|
|
results = append(results, k)
|
|
|
|
}
|
|
|
|
return results
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SimpleSet[T]) Clear() {
|
|
|
|
s.set = make(map[T]any)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SimpleSet[T]) Remove(t T) (removed bool) {
|
|
|
|
if !s.Contains(t) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
delete(s.set, t)
|
|
|
|
return true
|
|
|
|
}
|
2025-05-25 17:30:53 -04:00
|
|
|
|
|
|
|
func (s *SimpleSet[T]) RemoveSlice(slice []T) (removed []bool) {
|
|
|
|
removed = make([]bool, 0, len(slice))
|
|
|
|
for _, t := range slice {
|
|
|
|
removed = append(removed, s.Remove(t))
|
|
|
|
}
|
|
|
|
return removed
|
|
|
|
}
|