迭代器示例集合增加筛选功能
This commit is contained in:
parent
0ab01f3a8f
commit
d556abe081
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ func TestSet(t *testing.T) {
|
||||
"gopher",
|
||||
"javaer",
|
||||
}
|
||||
var pull, push []string
|
||||
var pull, push, filter []string
|
||||
expected := list[:3]
|
||||
for v := range slices.Values(list) {
|
||||
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, pull)
|
||||
assert.Equal(t, expected, filter)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user