Skip to content

Commit

Permalink
[TASK] TRK-784 Add filter function to gofp (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
Skandalik authored Oct 18, 2022
1 parent 6bacd07 commit 3da563d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
13 changes: 13 additions & 0 deletions gofp/filter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package gofp

// Filter apply a function to all elements on an array. Returns elements that are not filtered.
func Filter[T any](list []T, predicate func(T) bool) (res []T) {
res = make([]T, 0, len(list))
for i := range list {
if !predicate(list[i]) {
res = append(res, list[i])
}
}

return
}
37 changes: 37 additions & 0 deletions gofp/filter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package gofp_test

import (
"testing"

. "github.com/msales/gox/gofp"
)

func TestFilter_Int64(t *testing.T) {
got := Filter([]int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, func(v int64) bool {
return v%2 == 1
})

want := []int64{2, 4, 6, 8, 10}

if len(want) != len(got) {
t.Errorf("Got %+v, want %+v", got, want)
return
}

for k, v := range want {
if v != got[k] {
t.Errorf("Got %+v, want %+v", got, want)
}
}
}

func BenchmarkFilter_Int64(b *testing.B) {
original := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
b.ResetTimer()

for i := 0; i < b.N; i++ {
Filter(original, func(v int64) bool {
return v%2 == 1
})
}
}

0 comments on commit 3da563d

Please sign in to comment.