Skip to content

Commit 4042208

Browse files
authored
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>
1 parent 8c2f92f commit 4042208

File tree

4 files changed

+51
-0
lines changed

4 files changed

+51
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ make test
9191
- `Contains` (only numerics values at the moment)
9292
- `Each`
9393
- `Filter`
94+
- `Flatmap`
9495
- `Find`
9596
- `Map`
9697
- `Max`

docs/content/collections/flatmap.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
title: "Flatmap"
3+
date: 2022-08-10T16:49:56+02:00
4+
draft: false
5+
---
6+
7+
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.
8+
9+
```go
10+
package main
11+
12+
import (
13+
"fmt"
14+
u "github.com/rjNemo/underscore"
15+
)
16+
17+
func main() {
18+
nums := []int{1, 2, 3, 4}
19+
mapper := func(n int) []int { return []int{(n - 1) * n, (n) * n} }
20+
res := u.Flatmap(nums, mapper)
21+
fmt.Println(res) // {0, 1, 2, 4, 6, 9, 12, 16}
22+
}
23+
```

flatmap.go

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package underscore
2+
3+
// 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.
4+
func Flatmap[T any](values []T, mapper func(n T) []T) []T {
5+
res := make([]T, 0)
6+
for _, v := range values {
7+
vs := mapper(v)
8+
res = append(res, vs...)
9+
}
10+
return res
11+
}

flatmap_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package underscore_test
2+
3+
import (
4+
"testing"
5+
6+
u "github.com/rjNemo/underscore"
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestFlatmap(t *testing.T) {
11+
nums := []int{1, 2, 3, 4}
12+
transform := func(n int) []int { return []int{(n - 1) * n, (n) * n} }
13+
want := []int{0, 1, 2, 4, 6, 9, 12, 16}
14+
15+
assert.Equal(t, want, u.Flatmap(nums, transform))
16+
}

0 commit comments

Comments
 (0)