Skip to content

Commit 8ac424b

Browse files
add slice filter fn (#193)
1 parent 063af5c commit 8ac424b

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

slice/filter.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package slice
2+
3+
// Filter returns a sub-slice with all the elements that satisfy the fn condition.
4+
func Filter[T any](s []T, fn func(T) bool) []T {
5+
filtered := make([]T, 0, len(s))
6+
7+
for _, el := range s {
8+
if fn(el) {
9+
filtered = append(filtered, el)
10+
}
11+
}
12+
13+
return filtered
14+
}

slice/filter_test.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package slice
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestFilter(t *testing.T) {
10+
t.Run("logic", func(t *testing.T) {
11+
assert.Equal(t,
12+
[]string{"a", "c"},
13+
Filter(
14+
[]string{"a", "b", "c"},
15+
func(s string) bool { return s != "b" },
16+
))
17+
assert.Equal(t,
18+
[]int{1, 1},
19+
Filter(
20+
[]int{1, 10, 100, 1000, 100, 10, 1},
21+
func(i int) bool { return i < 10 },
22+
))
23+
24+
type item struct {
25+
price int
26+
condition string
27+
onDiscount bool
28+
}
29+
30+
assert.Len(t,
31+
Filter(
32+
[]item{
33+
{
34+
price: 115,
35+
condition: "new",
36+
onDiscount: true,
37+
},
38+
{
39+
price: 225,
40+
condition: "used",
41+
onDiscount: false,
42+
},
43+
{
44+
price: 335,
45+
condition: "mint",
46+
onDiscount: true,
47+
},
48+
},
49+
func(i item) bool { return i.onDiscount && i.condition != "used" && i.price < 300 },
50+
), 1,
51+
)
52+
})
53+
}

0 commit comments

Comments
 (0)