迭代器示例集合增加筛选功能

This commit is contained in:
fantasticbin 2024-11-12 15:34:44 +08:00
parent 0ab01f3a8f
commit d556abe081
2 changed files with 24 additions and 1 deletions

View File

@ -50,3 +50,18 @@ func (s *Set[T]) All() iter.Seq[T] {
} }
} }
} }
// FilterMap 筛选迭代
func (s *Set[T]) FilterMap(fn func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for _, v := range s.ordered {
if !fn(v) {
continue
}
if !yield(v) {
return
}
}
}
}

View File

@ -15,7 +15,7 @@ func TestSet(t *testing.T) {
"gopher", "gopher",
"javaer", "javaer",
} }
var pull, push []string var pull, push, filter []string
expected := list[:3] expected := list[:3]
for v := range slices.Values(list) { for v := range slices.Values(list) {
s.Add(v) s.Add(v)
@ -43,6 +43,14 @@ func TestSet(t *testing.T) {
} }
} }
// 筛选
for v := range s.FilterMap(func(v string) bool {
return v != "javaer"
}) {
filter = append(filter, v)
}
assert.Equal(t, expected, push) assert.Equal(t, expected, push)
assert.Equal(t, expected, pull) assert.Equal(t, expected, pull)
assert.Equal(t, expected, filter)
} }