From afb021b4b57bc2a9e8702f37352681968be521b8 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 8 Feb 2023 15:20:29 +0800 Subject: [PATCH] feat: add Max, Min for stream --- stream/stream.go | 35 +++++++++++++++++++++++++++++++++++ stream/stream_test.go | 22 ++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/stream/stream.go b/stream/stream.go index b4f71d8..aa13787 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -323,6 +323,41 @@ func (s stream[T]) Sorted(less func(a, b T) bool) stream[T] { return FromSlice(source) } +// Max returns the maximum element of this stream according to the provided less function. +// less: a > b +func (s stream[T]) Max(less func(a, b T) bool) (T, bool) { + var max T + + if len(s.source) == 0 { + return max, false + } + + for i, v := range s.source { + if less(v, max) || i == 0 { + max = v + } + } + return max, true +} + +// Min returns the minimum element of this stream according to the provided less function. +// less: a < b +func (s stream[T]) Min(less func(a, b T) bool) (T, bool) { + var min T + + if len(s.source) == 0 { + return min, false + } + + for i, v := range s.source { + if less(v, min) || i == 0 { + min = v + } + } + + return min, true +} + // ToSlice return the elements in the stream. func (s stream[T]) ToSlice() []T { return s.source diff --git a/stream/stream_test.go b/stream/stream_test.go index 0f62f7b..076d005 100644 --- a/stream/stream_test.go +++ b/stream/stream_test.go @@ -314,3 +314,25 @@ func TestStream_Sorted(t *testing.T) { assert.Equal([]int{4, 2, 1, 3}, s.ToSlice()) assert.Equal([]int{1, 2, 3, 4}, s1.ToSlice()) } + +func TestStream_Max(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_Max") + + s := FromSlice([]int{4, 2, 1, 3}) + + max, ok := s.Max(func(a, b int) bool { return a > b }) + + assert.Equal(4, max) + assert.Equal(true, ok) +} + +func TestStream_Min(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_Min") + + s := FromSlice([]int{4, 2, 1, 3}) + + max, ok := s.Max(func(a, b int) bool { return a < b }) + + assert.Equal(1, max) + assert.Equal(true, ok) +}