diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e76bd6c..3c215ef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,19 +4,18 @@ jobs: test: strategy: matrix: - go-version: [1.20.1, 1.21.1] + go-version: [1.20.x, 1.21.x, 1.22.x, 1.23.x, 1.24.x] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - - name: Install Go - uses: actions/setup-go@v3 - with: - go-version: ${{ matrix.go-version }} - stable: false - - name: Checkout code - uses: actions/checkout@v3 - - name: Test - run: | - go test -v -race ./... - # go vet ./... - # go test -bench=. \ No newline at end of file + - name: Install Go + uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go-version }} + - name: Checkout code + uses: actions/checkout@v4 + - name: Test + run: | + go test -v -race ./... + # go vet ./... + # go test -bench=. diff --git a/set.go b/set.go index 292089d..07cc80b 100644 --- a/set.go +++ b/set.go @@ -253,3 +253,13 @@ func NewThreadUnsafeSetFromMapKeys[T comparable, V any](val map[T]V) Set[T] { return s } + +// Elements returns an iterator that yields the elements of the set. Starting +// with Go 1.23, users can use a for loop to iterate over it. +func Elements[T comparable](s Set[T]) func(func(element T) bool) { + return func(yield func(element T) bool) { + s.Each(func(t T) bool { + return !yield(t) + }) + } +} diff --git a/set123_test.go b/set123_test.go new file mode 100644 index 0000000..df36506 --- /dev/null +++ b/set123_test.go @@ -0,0 +1,38 @@ +//go:build go1.23 +// +build go1.23 + +package mapset + +import ( + "testing" +) + +func Test_Elements123(t *testing.T) { + a := NewSet[string]() + + a.Add("Z") + a.Add("Y") + a.Add("X") + a.Add("W") + + b := NewSet[string]() + for elem := range Elements(a) { + b.Add(elem) + } + + if !a.Equal(b) { + t.Error("The sets are not equal after iterating (Each) through the first set") + } + + var count int + for range Elements(a) { + if count == 2 { + break + } + count++ + } + + if count != 2 { + t.Error("Iteration should stop on the way") + } +} diff --git a/set_test.go b/set_test.go index a21153d..5a17ca2 100644 --- a/set_test.go +++ b/set_test.go @@ -1346,6 +1346,38 @@ func Test_NewThreadUnsafeSetFromMapKey_Strings(t *testing.T) { } } +func Test_Elements(t *testing.T) { + a := NewSet[string]() + + a.Add("Z") + a.Add("Y") + a.Add("X") + a.Add("W") + + b := NewSet[string]() + Elements(a)(func(elem string) bool { + b.Add(elem) + return true + }) + + if !a.Equal(b) { + t.Error("The sets are not equal after iterating (Each) through the first set") + } + + var count int + Elements(a)(func(elem string) bool { + if count == 2 { + return false + } + count++ + return true + }) + + if count != 2 { + t.Error("Iteration should stop on the way") + } +} + func Test_Example(t *testing.T) { /* requiredClasses := NewSet()