// Package set defines a generic, mutable unordered set data structure. package set import "iter" // A Set is an implementation of an mutable, unordered set. It uses a Golang map // as its underlying data structure. type Set[T comparable] map[T]bool // Add appends a list of items into the set. func (s Set[T]) Add(items ...T) { for _, item := range items { s[item] = true } } // Has returns true an item is present in the set. func (s Set[T]) Has(item T) bool { return s[item] } // Remove deletes a list of items from the set. func (s Set[T]) Remove(items ...T) { for _, item := range items { delete(s, item) } } // Merge adds all items in the argument into the set. The argument is not // mutated. func (s Set[T]) Merge(o Set[T]) { for item := range o { s.Add(item) } } // ToList returns all items present in the set, as a slice. The order of the // items is not guaranteed. func (s Set[T]) ToList() []T { list := []T{} for item := range s { list = append(list, item) } return list } // Items returns a sequence of all items present in the set. The order of the // items is not guaranteed. func (s Set[T]) Items() iter.Seq[T] { return func(yield func(T) bool) { for item := range s { if !yield(item) { return } } } } // New creates a set of all items as argument. func New[T comparable](items ...T) Set[T] { result := Set[T]{} for _, item := range items { result.Add(item) } return result }