mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add FlatMap
This commit is contained in:
@@ -438,6 +438,18 @@ func FilterMap[T any, U any](slice []T, iteratee func(index int, item T) (U, boo
|
||||
return result
|
||||
}
|
||||
|
||||
// FlatMap manipulates a slice and transforms and flattens it to a slice of another type.
|
||||
// Play: todo
|
||||
func FlatMap[T any, U any](slice []T, iteratee func(index int, item T) []U) []U {
|
||||
result := make([]U, 0, len(slice))
|
||||
|
||||
for i, v := range slice {
|
||||
result = append(result, iteratee(i, v)...)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Reduce creates an slice of values by running each element of slice thru iteratee function.
|
||||
// Play: https://go.dev/play/p/_RfXJJWIsIm
|
||||
func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T {
|
||||
|
||||
@@ -386,6 +386,20 @@ func ExampleFilterMap() {
|
||||
// []string{"2", "4"}
|
||||
}
|
||||
|
||||
func ExampleFlatMap() {
|
||||
nums := []int{1, 2, 3, 4}
|
||||
|
||||
result := FlatMap(nums, func(i int, num int) []string {
|
||||
s := "hi-" + strconv.FormatInt(int64(num), 10)
|
||||
return []string{s}
|
||||
})
|
||||
|
||||
fmt.Printf("%#v", result)
|
||||
|
||||
// Output:
|
||||
// []string{"hi-1", "hi-2", "hi-3", "hi-4"}
|
||||
}
|
||||
|
||||
func ExampleReduce() {
|
||||
nums := []int{1, 2, 3}
|
||||
|
||||
|
||||
@@ -333,6 +333,19 @@ func TestFilterMap(t *testing.T) {
|
||||
assert.Equal([]string{"2", "4"}, result)
|
||||
}
|
||||
|
||||
func TestFlatMap(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestFlatMap")
|
||||
|
||||
nums := []int{1, 2, 3, 4}
|
||||
|
||||
result := FlatMap(nums, func(i int, num int) []string {
|
||||
s := "hi-" + strconv.FormatInt(int64(num), 10)
|
||||
return []string{s}
|
||||
})
|
||||
|
||||
assert.Equal([]string{"hi-1", "hi-2", "hi-3", "hi-4"}, result)
|
||||
}
|
||||
|
||||
func TestReduce(t *testing.T) {
|
||||
cases := [][]int{
|
||||
{},
|
||||
|
||||
Reference in New Issue
Block a user