github.com/djordje200179/extendedlibrary/datastructures@v1.7.1-0.20240227175559-d09520a92dd4/sets/mapset/set.go (about)

     1  package mapset
     2  
     3  import (
     4  	"cmp"
     5  	"github.com/djordje200179/extendedlibrary/datastructures/iter"
     6  	"github.com/djordje200179/extendedlibrary/datastructures/maps"
     7  	"github.com/djordje200179/extendedlibrary/datastructures/maps/hashmap"
     8  	"github.com/djordje200179/extendedlibrary/datastructures/maps/rbt"
     9  	"github.com/djordje200179/extendedlibrary/datastructures/sets"
    10  )
    11  
    12  type empty struct{}
    13  
    14  // Set is a set implementation based on maps.
    15  // Keys are elements of the set, and values are empty structs.
    16  type Set[T any] struct {
    17  	m maps.Map[T, empty]
    18  }
    19  
    20  // NewHashSet creates a new hash set for comparable types.
    21  func NewHashSet[T comparable]() Set[T] {
    22  	return FromMap[T](hashmap.New[T, empty]())
    23  }
    24  
    25  // NewTreeSet creates a new tree set for ordered types.
    26  func NewTreeSet[T cmp.Ordered]() Set[T] {
    27  	return FromMap[T](rbt.New[T, empty]())
    28  }
    29  
    30  // FromMap creates a new set from a map.
    31  func FromMap[T any](m maps.Map[T, empty]) Set[T] {
    32  	return Set[T]{m}
    33  }
    34  
    35  // Size returns the number of elements in the set.
    36  func (s Set[T]) Size() int {
    37  	return s.m.Size()
    38  }
    39  
    40  // Add adds a value to the set.
    41  func (s Set[T]) Add(value T) {
    42  	if !s.m.Contains(value) {
    43  		s.m.Set(value, empty{})
    44  	}
    45  }
    46  
    47  // Remove removes a value from the set.
    48  func (s Set[T]) Remove(value T) {
    49  	s.m.Remove(value)
    50  }
    51  
    52  // Contains returns true if the set contains the value.
    53  func (s Set[T]) Contains(value T) bool {
    54  	return s.m.Contains(value)
    55  }
    56  
    57  // Clear removes all elements from the set.
    58  func (s Set[T]) Clear() {
    59  	s.m.Clear()
    60  }
    61  
    62  // Clone returns a shallow copy of the set.
    63  func (s Set[T]) Clone() sets.Set[T] {
    64  	return FromMap[T](s.m.Clone())
    65  }
    66  
    67  // Iterator returns an iter.Iterator over the set.
    68  func (s Set[T]) Iterator() iter.Iterator[T] {
    69  	return s.SetIterator()
    70  }
    71  
    72  // SetIterator returns an iterator over the set.
    73  func (s Set[T]) SetIterator() sets.Iterator[T] {
    74  	return Iterator[T]{s.m.MapIterator()}
    75  }
    76  
    77  // Stream streams the elements of the Set.
    78  func (s Set[T]) Stream(yield func(T) bool) {
    79  	for k, _ := range s.m.Stream2 {
    80  		if !yield(k) {
    81  			return
    82  		}
    83  	}
    84  }
    85  
    86  // Map returns the underlying map.
    87  func (s Set[T]) Map() maps.Map[T, empty] {
    88  	return s.m
    89  }