Skip to content

Commit

Permalink
slice: return an iter.Seq from MatchingKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Sep 13, 2024
1 parent 7f7c844 commit 6a13e56
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 12 deletions.
3 changes: 1 addition & 2 deletions slice/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ func ExampleSplit() {
func ExampleMatchingKeys() {
vs := map[string]int{"red": 3, "yellow": 6, "blue": 4, "green": 5}

keys := slice.MatchingKeys(vs, isEven)
for _, key := range keys {
for key := range slice.MatchingKeys(vs, isEven) {
fmt.Println(key, vs[key])
}
// Unordered output:
Expand Down
23 changes: 14 additions & 9 deletions slice/slice.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// Package slice implements some useful functions for slices.
package slice

import "slices"
import (
"iter"
"slices"
)

// Partition rearranges the elements of vs in-place so that all the elements v
// for which keep(v) is true precede all those for which it is false. It
Expand Down Expand Up @@ -152,16 +155,18 @@ func PtrAt[T any, Slice ~[]T](ss Slice, i int) *T {
return nil
}

// MatchingKeys returns a slice of the keys k of m for which f(m[k]) is true.
// The resulting slice is in arbitrary order.
func MatchingKeys[T comparable, U any](m map[T]U, f func(U) bool) []T {
var out []T
for k, v := range m {
if f(v) {
out = append(out, k)
// MatchingKeys returns an iterator over the keys k of m for which f(m[k]) is
// true. The results are delivered in arbitrary order.
func MatchingKeys[T comparable, U any](m map[T]U, f func(U) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for k, v := range m {
if f(v) {
if !yield(k) {
return
}
}
}
}
return out
}

// Rotate permutes the elements of ss in-place by k positions.
Expand Down
5 changes: 4 additions & 1 deletion slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,10 @@ func TestMatchingKeys(t *testing.T) {
[]string{"a", "b", "c"}},
}
for _, tc := range tests {
got := slice.MatchingKeys(tc.m, tc.f)
var got []string
for key := range slice.MatchingKeys(tc.m, tc.f) {
got = append(got, key)
}
sort.Strings(got)
sort.Strings(tc.want)
if diff := cmp.Diff(tc.want, got); diff != "" {
Expand Down

0 comments on commit 6a13e56

Please sign in to comment.