Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,19 @@ func New[A comparable](as ...A) Set[A] {
}

// Add adds an element to the set.
func (s Set[A]) Add(a A) {
s[a] = struct{}{}
func (s *Set[A]) Add(a A) {
if *s == nil {
*s = New(a)
return
}
(*s)[a] = struct{}{}
}

// Contains checks if an element is in the set.
func (s Set[A]) Contains(a A) bool {
if s == nil {
return false
}
_, ok := s[a]
return ok
}
11 changes: 11 additions & 0 deletions set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,15 @@ func TestSet(t *testing.T) {
if s.Contains("xpp") {
t.Error("set contains xpp but this was never added")
}

var s2 Set[int]
s2.Add(2)
if !s2.Contains(2) {
t.Error("expected set to contain 2 but it did not")
}

var s3 Set[uint32]
if s3.Contains(2) {
t.Error("expected set to not contain 2 but it did")
}
}