From 49da23ca5f4fb321552f69a5cb4517bcf6941ed6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Str=C4=85czy=C5=84ski?= Date: Tue, 1 Jun 2021 09:34:31 +0200 Subject: [PATCH] Slice filtering fix. (#15) --- slicex/slice.go | 2 +- slicex/slice_test.go | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/slicex/slice.go b/slicex/slice.go index e3f2d9c..d24db0a 100644 --- a/slicex/slice.go +++ b/slicex/slice.go @@ -25,7 +25,7 @@ func Filter(x interface{}, filter func(i int) bool) { v := ptr.Elem() validateReflection("Filter", reflect.Slice, v) - for i := 0; i < v.Len(); i++ { + for i := v.Len() - 1; i >= 0; i-- { if filter(i) { v.Set(reflect.AppendSlice(v.Slice(0, i), v.Slice(i+1, v.Len()))) } diff --git a/slicex/slice_test.go b/slicex/slice_test.go index 2de7b43..d486ff4 100644 --- a/slicex/slice_test.go +++ b/slicex/slice_test.go @@ -111,6 +111,17 @@ func TestFilterInt_Filtered(t *testing.T) { } } +func TestFilterInt_AllFiltered(t *testing.T) { + slice := []int{2, 4, 6, 8} + want := []int{} + Filter(&slice, func(i int) bool { + return slice[i]%2 == 0 + }) + if !reflect.DeepEqual(want, slice) { + t.Errorf("Got %+v, want %+v", slice, want) + } +} + func TestFilterInt_NotFiltered(t *testing.T) { slice := []int{1, 2, 3} want := []int{1, 2, 3}