1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-10 15:52:27 +08:00

feat: add ReduceBy

This commit is contained in:
dudaodong
2023-04-04 17:41:37 +08:00
parent 8bdd46bda4
commit f198191063
5 changed files with 122 additions and 0 deletions

View File

@@ -63,6 +63,7 @@ import (
- [Merge](#Merge)
- [Reverse](#Reverse)
- [Reduce](#Reduce)
- [ReduceBy](#ReduceBy)
- [Replace](#Replace)
- [ReplaceAll](#ReplaceAll)
- [Repeat](#Repeat)
@@ -1504,6 +1505,43 @@ func main() {
}
```
### <span id="ReduceBy">ReduceBy</span>
<p>Produces a value from slice by accumulating the result of each element as passed through the reducer function.</p>
<b>Signature:</b>
```go
func ReduceBy[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U
```
<b>Example:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
result1 := slice.ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
return agg + item
})
result2 := slice.ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 10
// 1234
}
```
### <span id="Replace">Replace</span>
<p>Returns a copy of the slice with the first n non-overlapping instances of old replaced by new.</p>

View File

@@ -63,6 +63,7 @@ import (
- [Merge](#Merge)
- [Reverse](#Reverse)
- [Reduce](#Reduce)
- [ReduceBy](#ReduceBy)
- [Replace](#Replace)
- [ReplaceAll](#ReplaceAll)
- [Repeat](#Repeat)
@@ -1505,6 +1506,44 @@ func main() {
}
```
### <span id="ReduceBy">ReduceBy</span>
<p>对切片中执行reduce操作。</p>
<b>函数签名:</b>
```go
func ReduceBy[T any, U any](slice []T, initial U, reducer func(index int, item T, agg U) U) U
```
<b>示例:</b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
)
func main() {
result1 := slice.ReduceBy([]int{1, 2, 3, 4}, 0, func(_ int, item int, agg int) int {
return agg + item
})
result2 := slice.ReduceBy([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// 10
// 1234
}
```
### <span id="Replace">Replace</span>
<p>返回切片的副本其中前n个不重叠的old替换为new</p>