Skip to content

Commit

Permalink
Slice filtering fix. (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
rhstr authored Jun 1, 2021
1 parent cd9704a commit 49da23c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion slicex/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())))
}
Expand Down
11 changes: 11 additions & 0 deletions slicex/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down

0 comments on commit 49da23c

Please sign in to comment.