git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/set/set.go (about)

     1  package set
     2  
     3  type Set[T comparable] map[T]struct{}
     4  
     5  func New[T comparable](fromList []T) Set[T] {
     6  	ret := Set[T](make(map[T]struct{}))
     7  
     8  	for _, item := range fromList {
     9  		ret[item] = struct{}{}
    10  	}
    11  
    12  	return ret
    13  }
    14  
    15  func (set Set[T]) Contains(item T) bool {
    16  	_, contains := set[item]
    17  	return contains
    18  }
    19  
    20  func (set Set[T]) ToSlice() []T {
    21  	ret := make([]T, len(set))
    22  	i := 0
    23  
    24  	for elem := range set {
    25  		ret[i] = elem
    26  		i += 1
    27  	}
    28  
    29  	return ret
    30  }