From 0d11ce03a89d5f61e4fdcd2f41bd9e33b2140895 Mon Sep 17 00:00:00 2001 From: suplalalala <59185155+suplalalala@users.noreply.github.com> Date: Sun, 16 Apr 2023 23:14:25 +0800 Subject: [PATCH] feature: two evaluate operate func addtion in package stream (#3129) Co-authored-by: Riven --- core/fx/stream.go | 22 ++++++++++++ core/fx/stream_test.go | 77 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/core/fx/stream.go b/core/fx/stream.go index 44495f87..8a637164 100644 --- a/core/fx/stream.go +++ b/core/fx/stream.go @@ -540,3 +540,25 @@ func newOptions() *rxOptions { workers: defaultWorkers, } } + +// Max returns the maximum item from the underlying source. +func (s Stream) Max(less LessFunc) any { + var maxItem any = nil + for item := range s.source { + if maxItem == nil || less(maxItem, item) { + maxItem = item + } + } + return maxItem +} + +// Min returns the minimum item from the underlying source. +func (s Stream) Min(less LessFunc) any { + var minItem any = nil + for item := range s.source { + if minItem == nil || !less(minItem, item) { + minItem = item + } + } + return minItem +} diff --git a/core/fx/stream_test.go b/core/fx/stream_test.go index dd58d3e6..c6eaef56 100644 --- a/core/fx/stream_test.go +++ b/core/fx/stream_test.go @@ -503,6 +503,83 @@ func TestStream_Concat(t *testing.T) { }) } +func TestStream_Max(t *testing.T) { + runCheckedTest(t, func(t *testing.T) { + tests := []struct { + name string + elements []any + max any + }{ + { + name: "no elements with nil", + }, + { + name: "no elements", + elements: []any{}, + max: nil, + }, + { + name: "1 element", + elements: []any{1}, + max: 1, + }, + { + name: "multiple elements", + elements: []any{1, 2, 9, 5, 8}, + max: 9, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + val := Just(test.elements...).Max(func(a, b any) bool { + return a.(int) < b.(int) + }) + assetEqual(t, test.max, val) + }) + } + }) +} + +func TestStream_Min(t *testing.T) { + runCheckedTest(t, func(t *testing.T) { + tests := []struct { + name string + elements []any + min any + }{ + { + name: "no elements with nil", + min: nil, + }, + { + name: "no elements", + elements: []any{}, + min: nil, + }, + { + name: "1 element", + elements: []any{1}, + min: 1, + }, + { + name: "multiple elements", + elements: []any{-1, 1, 2, 9, 5, 8}, + min: -1, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + val := Just(test.elements...).Min(func(a, b any) bool { + return a.(int) < b.(int) + }) + assetEqual(t, test.min, val) + }) + } + }) +} + func BenchmarkParallelMapReduce(b *testing.B) { b.ReportAllocs()