-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
063af5c
commit 8ac424b
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
) | ||
}) | ||
} |