diff --git a/set.go b/set.go index 292089d..4e7da09 100644 --- a/set.go +++ b/set.go @@ -253,3 +253,26 @@ func NewThreadUnsafeSetFromMapKeys[T comparable, V any](val map[T]V) Set[T] { return s } + +// NewSetFromSeq creates and returns a new set with the values from an iterator. +// Operations on the resulting set are thread-safe. +func NewSetFromSeq[T comparable](seq func(func(T) bool)) Set[T] { + s := NewSetWithSize[T](0) + addAllFromSeq(s, seq) + return s +} + +// NewThreadUnsafeSetFromSeq creates and returns a new set with the given keys of the map. +// Operations on the resulting set are not thread-safe. +func NewThreadUnsafeSetFromSeq[T comparable](seq func(func(T) bool)) Set[T] { + s := NewThreadUnsafeSetWithSize[T](0) + addAllFromSeq(s, seq) + return s +} + +func addAllFromSeq[T comparable](s Set[T], seq func(func(T) bool)) { + seq(func(v T) bool { + s.Add(v) + return true + }) +} diff --git a/set_test.go b/set_test.go index a21153d..24fa08c 100644 --- a/set_test.go +++ b/set_test.go @@ -1346,6 +1346,54 @@ func Test_NewThreadUnsafeSetFromMapKey_Strings(t *testing.T) { } } +func Test_NewSetFromSeq(t *testing.T) { + values := []int{1, 2, 3} + + seq := func(yield func(int) bool) { + for _, v := range values { + if !yield(v) { + return + } + } + } + + s := NewSetFromSeq(seq) + + if len(values) != s.Cardinality() { + t.Errorf("Length of Set is not the same as the iterator. Expected: %d. Actual: %d", len(values), s.Cardinality()) + } + + for _, v := range values { + if !s.Contains(v) { + t.Errorf("Set is missing element: %v", v) + } + } +} + +func Test_NewThreadUnsafeSetFromSeq(t *testing.T) { + values := []int{1, 2, 3} + + seq := func(yield func(int) bool) { + for _, v := range values { + if !yield(v) { + return + } + } + } + + s := NewThreadUnsafeSetFromSeq(seq) + + if len(values) != s.Cardinality() { + t.Errorf("Length of Set is not the same as the iterator. Expected: %d. Actual: %d", len(values), s.Cardinality()) + } + + for _, v := range values { + if !s.Contains(v) { + t.Errorf("Set is missing element: %v", v) + } + } +} + func Test_Example(t *testing.T) { /* requiredClasses := NewSet()