Skip to content

Commit

Permalink
(feat) adding generic Filter function
Browse files Browse the repository at this point in the history
  • Loading branch information
csandeep committed Aug 6, 2024
1 parent 69247e0 commit 2477b16
Show file tree
Hide file tree
Showing 2 changed files with 41 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
}
31 changes: 30 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,28 @@ func Test_Map(t *testing.T) {
}
}
}

func Test_Filter(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)
}
}
{
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 2477b16

Please sign in to comment.