1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 07:02:29 +08:00

feat: add ReduceRight

This commit is contained in:
dudaodong
2023-04-04 17:54:54 +08:00
parent f198191063
commit c01c9d14b4
5 changed files with 95 additions and 3 deletions

View File

@@ -64,6 +64,7 @@ import (
- [Reverse](#Reverse)
- [Reduce](#Reduce)
- [ReduceBy](#ReduceBy)
- [ReduceRight](#ReduceRight)
- [Replace](#Replace)
- [ReplaceAll](#ReplaceAll)
- [Repeat](#Repeat)
@@ -1505,7 +1506,6 @@ 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>
@@ -1542,6 +1542,36 @@ func main() {
}
```
### <span id="ReduceRight">ReduceRight</span>
<p>ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left.</p>
<b>Signature:</b>
```go
func ReduceRight[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() {
result := slice.ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result)
// Output:
// 4321
}
```
### <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

@@ -64,6 +64,7 @@ import (
- [Reverse](#Reverse)
- [Reduce](#Reduce)
- [ReduceBy](#ReduceBy)
- [ReduceRight](#ReduceRight)
- [Replace](#Replace)
- [ReplaceAll](#ReplaceAll)
- [Repeat](#Repeat)
@@ -1506,7 +1507,6 @@ func main() {
}
```
### <span id="ReduceBy">ReduceBy</span>
<p>对切片中执行reduce操作。</p>
@@ -1543,6 +1543,35 @@ func main() {
}
```
### <span id="ReduceRight">ReduceRight</span>
<p>类似ReduceBy操作迭代切片元素顺序从右至左。</p>
<b>函数签名:</b>
```go
func ReduceRight[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() {
result := slice.ReduceRight([]int{1, 2, 3, 4}, "", func(_ int, item int, agg string) string {
return agg + fmt.Sprintf("%v", item)
})
fmt.Println(result)
// Output:
// 4321
}
```
### <span id="Replace">Replace</span>