sets/set.go

83 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-07-21 23:09:38 +02:00
package sets
import (
"sync"
)
2024-05-28 00:44:13 +02:00
// Set represents a set of values.
2023-07-21 23:09:38 +02:00
type Set[T comparable] struct {
store map[T]struct{}
mux sync.RWMutex
}
2024-05-28 00:44:13 +02:00
// New creates a new set.
2023-07-21 23:09:38 +02:00
func New[T comparable](data ...T) *Set[T] {
set := &Set[T]{
store: map[T]struct{}{},
}
for _, element := range data {
set.Insert(element)
}
return set
}
2024-05-28 00:50:19 +02:00
// NewFromSlice creates a new set from a slice.
func NewFromSlice[T comparable](data []T) *Set[T] {
return New[T](data...)
}
2024-05-28 00:44:13 +02:00
// Size returns number of elements in set.
2023-07-21 23:09:38 +02:00
func (s *Set[T]) Size() int {
s.mux.RLock()
defer s.mux.RUnlock()
return len(s.store)
}
2024-05-28 00:44:13 +02:00
// Contains checks whether the value is contained in the set.
2023-07-21 23:09:38 +02:00
func (s *Set[T]) Contains(val T) bool {
s.mux.RLock()
defer s.mux.RUnlock()
_, ok := s.store[val]
return ok
}
2024-05-28 00:44:13 +02:00
// Insert inserts a value into the set if the value was not already present.
2023-07-21 23:09:38 +02:00
func (s *Set[T]) Insert(val T) bool {
s.mux.Lock()
defer s.mux.Unlock()
if _, ok := s.store[val]; !ok {
s.store[val] = struct{}{}
return false
}
return true
}
2024-05-28 00:44:13 +02:00
// Delete removes a value from the set if the value was already present.
2023-07-21 23:09:38 +02:00
func (s *Set[T]) Delete(val T) bool {
s.mux.Lock()
defer s.mux.Unlock()
if _, ok := s.store[val]; ok {
delete(s.store, val)
return true
}
return false
}
2024-05-28 00:44:13 +02:00
// Slice returns a slice which contains the elements from the set.
2023-07-21 23:09:38 +02:00
func (s *Set[T]) Slice() []T {
s.mux.RLock()
defer s.mux.RUnlock()
elements := []T{}
for k := range s.store {
elements = append(elements, k)
}
return elements
}