Skip to content

Commit

Permalink
slice: add Select
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Oct 7, 2024
1 parent 74a75e8 commit 9227047
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
12 changes: 12 additions & 0 deletions slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,15 @@ func Tail[T any, Slice ~[]T](vs Slice, n int) Slice {
}
return vs[len(vs)-n:]
}

// Select returns an iterator over the elements v of vs for which f(v) is true,
// in the same order they occur in the input.
func Select[T any, Slice ~[]T](vs Slice, f func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for _, v := range vs {
if f(v) && !yield(v) {
return
}
}
}
}
26 changes: 26 additions & 0 deletions slice/slice_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package slice_test

import (
"slices"
"sort"
"strings"
"testing"
Expand Down Expand Up @@ -487,6 +488,31 @@ func TestTail(t *testing.T) {
}
}

func TestSelect(t *testing.T) {
tests := []struct {
input, want []int
}{
{nil, nil},
{[]int{}, nil},
{[]int{1}, nil},
{[]int{4}, []int{4}},
{[]int{1, 4}, []int{4}},
{[]int{4, 1}, []int{4}},
{[]int{1, 2, 3}, []int{2}},
{[]int{1, 2, 3, 2}, []int{2, 2}},
{[]int{8, 6, 7, 5, 3, 0, 9}, []int{8, 6, 0}},
{[]int{8, 8, 1, 1, 2, 3, 2}, []int{8, 8, 2, 2}},
}

isEven := func(z int) bool { return z%2 == 0 }
for _, tc := range tests {
got := slices.Collect(slice.Select(tc.input, isEven))
if diff := cmp.Diff(got, tc.want); diff != "" {
t.Errorf("Select %v (-got, +want):\n%s", tc.input, diff)
}
}
}

func (tc *testCase[T]) partition(t *testing.T) {
t.Helper()

Expand Down

0 comments on commit 9227047

Please sign in to comment.