nothing to see here
at main 1.2 kB view raw
1package hashset 2 3import ( 4 "maps" 5) 6 7type Set[T comparable] map[T]struct{} 8 9// New creates and returns a new empty Set. 10func New[T comparable]() Set[T] { 11 return make(Set[T]) 12} 13 14// Add inserts an element into the set. 15func (s Set[T]) Add(value T) { 16 s[value] = struct{}{} 17} 18 19// Remove deletes an element from the set. 20func (s Set[T]) Remove(value T) { 21 delete(s, value) 22} 23 24// Size returns the number of elements in the set. 25func (s Set[T]) Size() int { 26 return len(s) 27} 28 29// Union returns a new set containing all elements from s and other. 30func (s Set[T]) Union(other Set[T]) Set[T] { 31 result := make(Set[T], len(s)+len(other)) 32 maps.Copy(result, s) 33 maps.Copy(result, other) 34 return result 35} 36 37// Intersection returns a new set containing elements common to s and other. 38func (s Set[T]) Intersection(other Set[T]) Set[T] { 39 result := New[T]() 40 for k := range s { 41 if _, ok := other[k]; ok { 42 result.Add(k) 43 } 44 } 45 return result 46} 47 48// Difference returns a new set with elements in s but not in other. 49func (s Set[T]) Difference(other Set[T]) Set[T] { 50 result := New[T]() 51 for k := range s { 52 if _, ok := other[k]; !ok { 53 result.Add(k) 54 } 55 } 56 return result 57}