add flatmap (#31)

* add flatmap

Signed-off-by: Ruidy <ruidy.nemausat@gmail.com>

* add to readme

Signed-off-by: Ruidy <ruidy.nemausat@gmail.com>

Signed-off-by: Ruidy <ruidy.nemausat@gmail.com>
Co-authored-by: Ruidy <ruidy.nemausat@gmail.com>
This commit is contained in:
Ruidy 2022-08-10 17:01:43 +02:00 committed by GitHub
parent 8c2f92f202
commit 4042208482
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 51 additions and 0 deletions

View file

@ -91,6 +91,7 @@ make test
- `Contains` (only numerics values at the moment)
- `Each`
- `Filter`
- `Flatmap`
- `Find`
- `Map`
- `Max`

View file

@ -0,0 +1,23 @@
---
title: "Flatmap"
date: 2022-08-10T16:49:56+02:00
draft: false
---
Flatmap flattens the input slice element into the new slice. FlatMap maps every element with the help of a mapper function, then flattens the input slice element into the new slice.
```go
package main
import (
"fmt"
u "github.com/rjNemo/underscore"
)
func main() {
nums := []int{1, 2, 3, 4}
mapper := func(n int) []int { return []int{(n - 1) * n, (n) * n} }
res := u.Flatmap(nums, mapper)
fmt.Println(res) // {0, 1, 2, 4, 6, 9, 12, 16}
}
```

11
flatmap.go Normal file
View file

@ -0,0 +1,11 @@
package underscore
// Flatmap flatten the input slice element into the new slice. FlatMap maps every element with the help of a mapper function, then flattens the input slice element into the new slice.
func Flatmap[T any](values []T, mapper func(n T) []T) []T {
res := make([]T, 0)
for _, v := range values {
vs := mapper(v)
res = append(res, vs...)
}
return res
}

16
flatmap_test.go Normal file
View file

@ -0,0 +1,16 @@
package underscore_test
import (
"testing"
u "github.com/rjNemo/underscore"
"github.com/stretchr/testify/assert"
)
func TestFlatmap(t *testing.T) {
nums := []int{1, 2, 3, 4}
transform := func(n int) []int { return []int{(n - 1) * n, (n) * n} }
want := []int{0, 1, 2, 4, 6, 9, 12, 16}
assert.Equal(t, want, u.Flatmap(nums, transform))
}