Skip to content

Commit

Permalink
Make Filter() preserve type. (#365)
Browse files Browse the repository at this point in the history
* Update slice.go

* add test
  • Loading branch information
FGasper authored Jun 29, 2024
1 parent 2ec43f4 commit de419c7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (

// Filter iterates over elements of collection, returning an array of all elements predicate returns truthy for.
// Play: https://go.dev/play/p/Apjg3WeSi7K
func Filter[V any](collection []V, predicate func(item V, index int) bool) []V {
result := make([]V, 0, len(collection))
func Filter[V any, VC ~[]V](collection VC, predicate func(item V, index int) bool) VC {
result := make(VC, 0, len(collection))

for i := range collection {
if predicate(collection[i], i) {
Expand Down
7 changes: 7 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ func TestFilter(t *testing.T) {
})

is.Equal(r2, []string{"foo", "bar"})

type myStrings []string
allStrings := myStrings{"", "foo", "bar"}
nonempty := Filter(allStrings, func(x string, _ int) bool {
return len(x) > 0
})
is.IsType(nonempty, allStrings, "type preserved")
}

func TestMap(t *testing.T) {
Expand Down

0 comments on commit de419c7

Please sign in to comment.