Skip to content

Commit

Permalink
fixed resuce [the third element is not skipped now]
Browse files Browse the repository at this point in the history
  • Loading branch information
Dmitry Kossovich committed Dec 11, 2022
1 parent 94f36af commit 7d4d73d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
4 changes: 2 additions & 2 deletions pkg/pipe/pipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ func (p *Pipe[T]) Reduce(fn func(T, T) T) *T {
return &data[0]
default:
res := data[0]
for i := range data[1:] {
res = fn(res, data[i+1])
for _, val := range data[1:] {
res = fn(res, val)
}
return &res
}
Expand Down
28 changes: 28 additions & 0 deletions pkg/pipe/pipe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,31 @@ func TestSort_ok_parallel_large(t *testing.T) {
require.GreaterOrEqual(t, item, prevItem)
}
}

func TestReduce(t *testing.T) {
res := pipe.Func(func(i int) (int, bool) {
return i, true
}).
Gen(6000).
Reduce(func(a, b int) int { return a + b })

expected := 0
for i := 1; i < 6000; i++ {
expected += i
}
require.Equal(t, expected, *res)
}

func TestSum(t *testing.T) {
res := pipe.Func(func(i int) (int, bool) {
return i, true
}).
Gen(6000).
Sum(func(a, b int) int { return a + b })

expected := 0
for i := 1; i < 6000; i++ {
expected += i
}
require.Equal(t, expected, *res)
}
2 changes: 1 addition & 1 deletion pkg/pipe/prefixpipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func Reduce[SrcT any, DstT any](p *Pipe[SrcT], fn func(DstT, SrcT) DstT, initVal
default:
res := fn(initVal, data[0])
for i := range data[1:] {
res = fn(res, data[i+1])
res = fn(res, data[i])
}
return res
}
Expand Down

0 comments on commit 7d4d73d

Please sign in to comment.