Skip to content

Commit

Permalink
add slice filter fn (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikoskarakostas authored Dec 14, 2022
1 parent 063af5c commit 8ac424b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
14 changes: 14 additions & 0 deletions slice/filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package slice

// Filter returns a sub-slice with all the elements that satisfy the fn condition.
func Filter[T any](s []T, fn func(T) bool) []T {
filtered := make([]T, 0, len(s))

for _, el := range s {
if fn(el) {
filtered = append(filtered, el)
}
}

return filtered
}
53 changes: 53 additions & 0 deletions slice/filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package slice

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestFilter(t *testing.T) {
t.Run("logic", func(t *testing.T) {
assert.Equal(t,
[]string{"a", "c"},
Filter(
[]string{"a", "b", "c"},
func(s string) bool { return s != "b" },
))
assert.Equal(t,
[]int{1, 1},
Filter(
[]int{1, 10, 100, 1000, 100, 10, 1},
func(i int) bool { return i < 10 },
))

type item struct {
price int
condition string
onDiscount bool
}

assert.Len(t,
Filter(
[]item{
{
price: 115,
condition: "new",
onDiscount: true,
},
{
price: 225,
condition: "used",
onDiscount: false,
},
{
price: 335,
condition: "mint",
onDiscount: true,
},
},
func(i item) bool { return i.onDiscount && i.condition != "used" && i.price < 300 },
), 1,
)
})
}

0 comments on commit 8ac424b

Please sign in to comment.