Skip to content
Open
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
23 changes: 23 additions & 0 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
}
48 changes: 48 additions & 0 deletions set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down