Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: change slice.Reduce return type #3

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,12 @@ func Map[T any, R any, F MapFunc[T, R]](ss []T, funcInterface F) []R {
return result
}

type AccumulatorFunc[T any] func(acc T, i int, s T) T
type AccumulatorFunc[T any, R any] interface {
~func(acc R, i int, s T) R
}

// Reduce (aka inject) iterates over the slice of items and calls the accumulator function for each pass, storing the state in the acc variable through each pass.
func Reduce[T any](items []T, initialAccumulator T, f AccumulatorFunc[T]) T {
func Reduce[T any, R any, F AccumulatorFunc[T, R]](items []T, initialAccumulator R, f F) R {
if items == nil {
return initialAccumulator
}
Expand Down
18 changes: 18 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,24 @@ func TestReduce(t *testing.T) {
})

require.Equal(t, "55", result)

type OddEven struct {
Odd int
Even int
}

s2 := []int{0, 1, 2, 3, 4}

result2 := slice.Reduce(s2, OddEven{}, func(acc OddEven, i int, s int) OddEven {
if s%2 == 0 {
acc.Even++
} else {
acc.Odd++
}
return acc
})

require.Equal(t, OddEven{Odd: 2, Even: 3}, result2)
}

func TestSelect(t *testing.T) {
Expand Down