mirror of
https://github.com/samber/lo.git
synced 2026-04-22 23:47:11 +08:00
1.4 KiB
1.4 KiB
name, slug, sourceRef, category, subCategory, signatures, playUrl, variantHelpers, similarHelpers, position
| name | slug | sourceRef | category | subCategory | signatures | playUrl | variantHelpers | similarHelpers | position | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Reduce | reduce | it/seq.go#L133 | it | sequence |
|
https://go.dev/play/p/FmkVUf39ZP_Y |
|
|
30 |
Reduces a collection to a single accumulated value by applying an accumulator function to each element starting with an initial value.
Reduce
seq := func(yield func(int) bool) {
_ = yield(1)
_ = yield(2)
_ = yield(3)
_ = yield(4)
}
sum := it.Reduce(seq, func(acc int, item int) int {
return acc + item
}, 0)
// sum == 10
seq := func(yield func(string) bool) {
_ = yield("hello")
_ = yield("world")
}
concat := it.Reduce(seq, func(acc string, item string) string {
return acc + " " + item
}, "")
// concat == " hello world"
ReduceI
Reduces a collection to a single value by iterating through elements and applying an accumulator function that includes the index.
result := it.ReduceI(it.Range(1, 5), func(agg int, item int, index int) int {
return agg + item*index
}, 0)
// 20 (0*0 + 1*1 + 2*2 + 3*3)