mirror of
https://github.com/duke-git/lancet.git
synced 2026-03-01 00:35:28 +08:00
feat: add ForEach, Reduce for stream
This commit is contained in:
@@ -34,7 +34,7 @@ import (
|
|||||||
// AnyMatch(predicate func(item T) bool) bool
|
// AnyMatch(predicate func(item T) bool) bool
|
||||||
// NoneMatch(predicate func(item T) bool) bool
|
// NoneMatch(predicate func(item T) bool) bool
|
||||||
// ForEach(consumer func(item T))
|
// ForEach(consumer func(item T))
|
||||||
// Reduce(accumulator func(a, b T) T) (T, bool)
|
// Reduce(accumulator func(a, b T) T) T
|
||||||
// Count() int
|
// Count() int
|
||||||
|
|
||||||
// FindFirst() (T, bool)
|
// FindFirst() (T, bool)
|
||||||
@@ -234,6 +234,22 @@ func (s stream[T]) NoneMatch(predicate func(item T) bool) bool {
|
|||||||
return !s.AnyMatch(predicate)
|
return !s.AnyMatch(predicate)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ForEach performs an action for each element of this stream.
|
||||||
|
func (s stream[T]) ForEach(action func(item T)) {
|
||||||
|
for _, v := range s.source {
|
||||||
|
action(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reduce performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
|
||||||
|
func (s stream[T]) Reduce(init T, accumulator func(a, b T) T) T {
|
||||||
|
for _, v := range s.source {
|
||||||
|
init = accumulator(init, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return init
|
||||||
|
}
|
||||||
|
|
||||||
// Count returns the count of elements in the stream.
|
// Count returns the count of elements in the stream.
|
||||||
func (s stream[T]) Count() int {
|
func (s stream[T]) Count() int {
|
||||||
return len(s.source)
|
return len(s.source)
|
||||||
|
|||||||
@@ -222,3 +222,28 @@ func TestStream_NoneMatch(t *testing.T) {
|
|||||||
assert.Equal(true, result1)
|
assert.Equal(true, result1)
|
||||||
assert.Equal(false, result2)
|
assert.Equal(false, result2)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStream_ForEach(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestStream_ForEach")
|
||||||
|
|
||||||
|
stream := FromSlice([]int{1, 2, 3})
|
||||||
|
|
||||||
|
result := 0
|
||||||
|
stream.ForEach(func(item int) {
|
||||||
|
result += item
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(6, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStream_Reduce(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestStream_Reduce")
|
||||||
|
|
||||||
|
stream := FromSlice([]int{1, 2, 3})
|
||||||
|
|
||||||
|
result := stream.Reduce(0, func(a, b int) int {
|
||||||
|
return a + b
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(6, result)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user