Skip to content

Commit

Permalink
Merge pull request #15 from calvinbrown085/adding-map-filter
Browse files Browse the repository at this point in the history
Adding MapFilter for transform and filter
  • Loading branch information
orsinium authored Jul 20, 2023
2 parents d104098 + 1ce5a48 commit 7af1a11
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
15 changes: 15 additions & 0 deletions slices/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,21 @@ func ExampleMap() {
// Output: [8 16 30 32 46 84]
}

func ExampleMapFilter() {
s := []int{4, 8, 15, 16, 23, 42}
isEven := func(t int) (string, bool) {
if t%2 == 0 {
s := fmt.Sprintf("%d", t)
return s, true
} else {
return "", false
}

}
doubled := slices.MapFilter(s, isEven)
fmt.Println(doubled)
// Output: [4 8 16 42]
}
func ExampleMapAsync() {
pages := slices.MapAsync(
[]string{"google.com", "go.dev", "golang.org"},
Expand Down
12 changes: 12 additions & 0 deletions slices/slice_func.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,18 @@ func Map[S ~[]T, T any, G any](items S, f func(el T) G) []G {
return result
}

// Map applies F to all elements in slice of T and returns slice results as pointers, and will filter out the non-nil ones.
func MapFilter[S ~[]T, T any, G any](items S, f func(el T) (G, bool)) []G {
result := make([]G, 0, len(items))
for _, el := range items {
r, b := f(el)
if b {
result = append(result, r)
}
}
return result
}

// Reduce applies F to acc and every element in slice of T and returns acc
func Reduce[S ~[]T, T any, G any](items S, acc G, f func(el T, acc G) G) G {
for _, el := range items {
Expand Down
20 changes: 20 additions & 0 deletions slices/slice_func_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package slices_test

import (
"fmt"
"testing"

"github.com/life4/genesis/slices"
Expand Down Expand Up @@ -164,6 +165,25 @@ func TestMap(t *testing.T) {
f([]int{1, 2, 3}, []int{2, 4, 6})
}

func TestMapFilter(t *testing.T) {
is := is.New(t)
f := func(given []int, expected []string) {
isEven := func(t int) (string, bool) {
if t%2 == 0 {
s := fmt.Sprintf("%d", t)
return s, true
} else {
return "", false
}

}
actual := slices.MapFilter(given, isEven)
is.Equal(expected, actual)
}
f([]int{}, []string{})
f([]int{1}, []string{})
f([]int{1, 2, 3, 4}, []string{"2", "4"})
}
func TestReduce(t *testing.T) {
is := is.New(t)
f := func(given []int, expected int) {
Expand Down

0 comments on commit 7af1a11

Please sign in to comment.