Skip to content

Commit

Permalink
feat(higherorder): adding generic Filter function (#141)
Browse files Browse the repository at this point in the history
* feat(higherorder): adding generic Filter function
* fix(higherorder): with re-factored test for Filter
  • Loading branch information
csandeep authored Aug 6, 2024
1 parent 69247e0 commit c5da01e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
11 changes: 11 additions & 0 deletions exp/higherorder/higherorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,14 @@ func Map[A, B any](f func(A) B, list []A) []B {
}
return res
}

// Filter applies a function to each element of a list, if the function returns false those elements are removed, returning a new list
func Filter[A any](f func(A) bool, list []A) []A {
res := make([]A, 0)
for _, v := range list {
if f(v) {
res = append(res, v)
}
}
return res
}
32 changes: 31 additions & 1 deletion exp/higherorder/higherorder_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package higherorder

import "testing"
import (
"reflect"
"strings"
"testing"
)

func Test_Foldl(t *testing.T) {
x := Foldl(func(a, b int) int {
Expand Down Expand Up @@ -54,3 +58,29 @@ func Test_Map(t *testing.T) {
}
}
}

func Test_Filter(t *testing.T) {
t.Run("with string slices", func(t *testing.T) {
got := Filter(func(a string) bool {
return strings.HasPrefix(a, "t")
}, []string{"one", "two", "three"})

want := []string{"two", "three"}

if !reflect.DeepEqual(got, want) {
t.Errorf("Expected %v, got %v", want, got)
}
})

t.Run("with int slices", func(t *testing.T) {
got := Filter(func(a int) bool {
return a%2 == 0
}, []int{1, 2, 3, 4, 5})

want := []int{2, 4}

if !reflect.DeepEqual(got, want) {
t.Errorf("Expected %v, got %v", want, got)
}
})
}

0 comments on commit c5da01e

Please sign in to comment.