From ad518df9936e7a4cc783ee3dd9d66319c3112bf2 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Tue, 28 Dec 2021 19:36:36 -0400 Subject: [PATCH] feat: filter --- filter.go | 10 ++++++++++ filter_test.go | 17 +++++++++++++++++ go.mod | 4 ++-- go.sum | 4 +--- 4 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 filter.go create mode 100644 filter_test.go diff --git a/filter.go b/filter.go new file mode 100644 index 0000000..f277cb4 --- /dev/null +++ b/filter.go @@ -0,0 +1,10 @@ +package underscore + +func Filter[T any](values []T, predicate func(T) bool) (res []T) { + for _, v := range values { + if predicate(v) { + res = append(res, v) + } + } + return res +} diff --git a/filter_test.go b/filter_test.go new file mode 100644 index 0000000..fdd8e6b --- /dev/null +++ b/filter_test.go @@ -0,0 +1,17 @@ +package underscore_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + u "github.com/rjNemo/underscore" +) + +func TestFilter(t *testing.T) { + nums := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + isEven := func(n int) bool { return n%2 == 0 } + + want := []int{0, 2, 4, 6, 8} + assert.Equal(t, want, u.Filter(nums, isEven)) +} diff --git a/go.mod b/go.mod index 0066efa..98452a0 100644 --- a/go.mod +++ b/go.mod @@ -2,10 +2,10 @@ module github.com/rjNemo/underscore go 1.18 +require github.com/stretchr/testify v1.7.0 + require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/objx v0.3.0 // indirect - github.com/stretchr/testify v1.7.0 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) diff --git a/go.sum b/go.sum index 8d71661..c221f64 100644 --- a/go.sum +++ b/go.sum @@ -4,11 +4,9 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As= -github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=