diff --git a/filter.go b/filter.go index 92e1dc8..77088aa 100644 --- a/filter.go +++ b/filter.go @@ -4,8 +4,8 @@ import "context" // Filter takes an array of T's and applies the callback fn to each element. // If fn returns true, the element is included in the returned collection, if false it is excluded. -// Example: [1, 2, 3].Filter() = [1, 3]. func Filter[T any](arr []T, fn func(T) bool) (out []T) { + out = make([]T, 0) for _, elem := range arr { if fn(elem) { out = append(out, elem) @@ -20,6 +20,7 @@ func FilterContext[T any]( arr []T, fn func(ctx context.Context, elem T) bool, ) (out []T) { + out = make([]T, 0) for _, elem := range arr { if fn(ctx, elem) { out = append(out, elem) @@ -33,6 +34,7 @@ func FilterError[T any]( arr []T, fn func(elem T) (bool, error), ) (out []T, err error) { + out = make([]T, 0) for _, elem := range arr { include, err := fn(elem) if err != nil { @@ -52,6 +54,7 @@ func FilterContextError[T any]( arr []T, fn func(ctx context.Context, elem T) (bool, error), ) (out []T, err error) { + out = make([]T, 0) for _, elem := range arr { include, err := fn(ctx, elem) if err != nil { diff --git a/filter_test.go b/filter_test.go index 16c9d45..2662d7d 100644 --- a/filter_test.go +++ b/filter_test.go @@ -8,6 +8,26 @@ import ( "github.com/stretchr/testify/require" ) +func ExampleFilter() { + fmt.Println( + Filter( + []int{1, 2, 3}, func(item int) bool { + return item%2 != 0 + }, + ), + ) + fmt.Println( + Filter( + []int{1, 2, 3}, func(item int) bool { + return item > 10 + }, + ), + ) + // Output: + // [1 3] + // [] +} + func TestFilterInts(t *testing.T) { ints := []int{1, 2, 3, 4, 5} filtered := Filter( @@ -18,6 +38,17 @@ func TestFilterInts(t *testing.T) { require.ElementsMatch(t, filtered, []int{2, 4}) } +func TestFilterInts_NoMatches(t *testing.T) { + ints := []int{1, 2, 3} + filtered := Filter( + ints, func(i int) bool { + return i > 10 + }, + ) + require.ElementsMatch(t, filtered, []int{}) + require.Equal(t, []int{}, filtered) +} + func TestFilterStrings(t *testing.T) { strings := []string{"a", "bb", "ccc", "dddd"} filtered := Filter(