Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(<number is odd?>) = [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)
Expand All @@ -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)
Expand All @@ -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 {
Expand All @@ -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 {
Expand Down
31 changes: 31 additions & 0 deletions filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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(
Expand Down