Skip to content

Commit

Permalink
Add set.Collect and set.Of[T].AddSeq.
Browse files Browse the repository at this point in the history
  • Loading branch information
bobg committed Aug 15, 2024
1 parent fd36824 commit c2b6abc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
16 changes: 15 additions & 1 deletion set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ func New[T comparable](vals ...T) Of[T] {
return Of[T](s)
}

// Collect collects the members of the given sequence into a new set.
func Collect[T comparable](inp iter.Seq[T]) Of[T] {
s := New[T]()
s.AddSeq(inp)
return s
}

// Add adds the given values to the set.
// Items already present in the set are silently ignored.
func (s Of[T]) Add(vals ...T) {
Expand All @@ -33,6 +40,13 @@ func (s Of[T]) Add(vals ...T) {
}
}

// AddSeq adds the members of the given sequence to the set.
func (s Of[T]) AddSeq(inp iter.Seq[T]) {
for val := range inp {
s.Add(val)
}
}

// Has tells whether the given value is in the set.
// The set may be nil.
func (s Of[T]) Has(val T) bool {
Expand Down Expand Up @@ -72,7 +86,7 @@ func (s Of[T]) Equal(other Of[T]) bool {
// returns true. If the function does not return true for any value
// in the set, Find returns false and the zero value of T.
//
// if several set elements would match, the first match will be chosen
// If several set elements would match, the first match will be chosen
// arbitrarily because the iteration order is indeterminate.
//
// Find can also be used for two special cases:
Expand Down
12 changes: 12 additions & 0 deletions set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package set

import (
"reflect"
"slices"
"testing"
)

Expand Down Expand Up @@ -103,3 +104,14 @@ func TestEqual(t *testing.T) {
t.Error("got d == a")
}
}

func TestCollect(t *testing.T) {
var (
nums = slices.Values([]int{1, 2, 3, 4, 5, 6})
got = Collect(nums)
want = New[int](1, 2, 3, 4, 5, 6)
)
if !got.Equal(want) {
t.Errorf("got %v, want %v", got, want)
}
}

0 comments on commit c2b6abc

Please sign in to comment.