1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-13 01:02:28 +08:00

feat: add ForEach, Reduce for stream

This commit is contained in:
dudaodong
2023-02-06 17:38:33 +08:00
parent b4b9b03835
commit 09a379ec6d
2 changed files with 42 additions and 1 deletions

View File

@@ -34,7 +34,7 @@ import (
// AnyMatch(predicate func(item T) bool) bool
// NoneMatch(predicate func(item T) bool) bool
// ForEach(consumer func(item T))
// Reduce(accumulator func(a, b T) T) (T, bool)
// Reduce(accumulator func(a, b T) T) T
// Count() int
// FindFirst() (T, bool)
@@ -234,6 +234,22 @@ func (s stream[T]) NoneMatch(predicate func(item T) bool) bool {
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.
func (s stream[T]) Count() int {
return len(s.source)