From d556abe0816ae0f4ad896b929f15706a6cad4838 Mon Sep 17 00:00:00 2001 From: fantasticbin Date: Tue, 12 Nov 2024 15:34:44 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=AD=E4=BB=A3=E5=99=A8=E7=A4=BA=E4=BE=8B?= =?UTF-8?q?=E9=9B=86=E5=90=88=E5=A2=9E=E5=8A=A0=E7=AD=9B=E9=80=89=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- iterator/set.go | 15 +++++++++++++++ iterator/set_test.go | 10 +++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/iterator/set.go b/iterator/set.go index e469724..350d24e 100644 --- a/iterator/set.go +++ b/iterator/set.go @@ -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 + } + } + } +} diff --git a/iterator/set_test.go b/iterator/set_test.go index a3ba3b8..74947ac 100644 --- a/iterator/set_test.go +++ b/iterator/set_test.go @@ -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) }