docs: set

This commit is contained in:
2026-02-07 21:10:27 -05:00
parent 4171f0ccb2
commit 2a028d95ec

View File

@@ -1,31 +1,41 @@
// 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{}
@@ -36,6 +46,8 @@ func (s Set[T]) ToList() []T {
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 {
@@ -46,6 +58,7 @@ func (s Set[T]) Items() iter.Seq[T] {
}
}
// New creates a set of all items as argument.
func New[T comparable](items ...T) Set[T] {
result := Set[T]{}