set.go

v0.1.0
Doc Versions Source
1
package set
2
3
import "sourcecraft.dev/bigbes/auxilia/collect"
4
5
// Set is a generic set backed by map[T]struct{}.
6
type Set[T comparable] struct {
7
	internal map[T]struct{}
8
}
9
10
// NewSet creates an empty set with a capacity hint.
11
func NewSet[T comparable](expectedSize int) Set[T] {
12
	return Set[T]{internal: make(map[T]struct{}, expectedSize)}
13
}
14
15
// NewSetFromListFunc creates a set by applying f to each element of inp.
16
func NewSetFromListFunc[I any, T comparable](inp []I, f func(I) T) Set[T] {
17
	s := NewSet[T](len(inp))
18
	for _, item := range inp {
19
		s.Add(f(item))
20
	}
21
	return s
22
}
23
24
// Add inserts key into the set. It returns true if the key was newly added.
25
func (s *Set[T]) Add(key T) bool {
26
	if _, exists := s.internal[key]; exists {
27
		return false
28
	}
29
	s.internal[key] = struct{}{}
30
	return true
31
}
32
33
// Len returns the number of elements in the set.
34
func (s Set[T]) Len() int {
35
	return len(s.internal)
36
}
37
38
// Has reports whether key is in the set.
39
func (s Set[T]) Has(key T) bool {
40
	_, ok := s.internal[key]
41
	return ok
42
}
43
44
// Delete removes key from the set. It returns true if the key existed.
45
func (s Set[T]) Delete(key T) bool {
46
	if _, ok := s.internal[key]; !ok {
47
		return false
48
	}
49
	delete(s.internal, key)
50
	return true
51
}
52
53
// Iterator returns a [collect.ListIterator] over the set elements.
54
// The iteration order is not guaranteed.
55
func (s Set[T]) Iterator() collect.ListIterator[T] {
56
	keys := make([]T, 0, len(s.internal))
57
	for k := range s.internal {
58
		keys = append(keys, k)
59
	}
60
	return collect.FromSlice(keys)
61
}
62

Source Files