From 1616d3d1be54a91ab8d414f578c872828bfedf94 Mon Sep 17 00:00:00 2001 From: will <3051227558@qq.com> Date: Thu, 18 May 2023 10:17:15 +0800 Subject: [PATCH] feat:addFindLast for stream (#95) Co-authored-by: sunyaoyao --- stream/stream.go | 12 ++++++++++++ stream/stream_example_test.go | 13 +++++++++++++ stream/stream_test.go | 18 ++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/stream/stream.go b/stream/stream.go index 23734a3..cc6b471 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -295,6 +295,18 @@ func (s stream[T]) FindFirst() (T, bool) { return s.source[0], true } +// FindLast returns the last element of this stream and true, or zero value and false if the stream is empty. +// Play: https://go.dev/play/p/9xEf0-6C1e3 +func (s stream[T]) FindLast() (T, bool) { + var result T + + if s.source == nil || len(s.source) == 0 { + return result, false + } + + return s.source[len(s.source)-1], true +} + // Reverse returns a stream whose elements are reverse order of given stream. // Play: https://go.dev/play/p/A8_zkJnLHm4 func (s stream[T]) Reverse() stream[T] { diff --git a/stream/stream_example_test.go b/stream/stream_example_test.go index 4842071..b854dfd 100644 --- a/stream/stream_example_test.go +++ b/stream/stream_example_test.go @@ -290,6 +290,19 @@ func ExampleStream_FindFirst() { // true } +func ExampleStream_FindLast() { + original := FromSlice([]int{3, 2, 1}) + + result, ok := original.FindLast() + + fmt.Println(result) + fmt.Println(ok) + + // Output: + // 1 + // true +} + func ExampleStream_Reverse() { original := FromSlice([]int{1, 2, 3}) diff --git a/stream/stream_test.go b/stream/stream_test.go index 6523cce..b749f5d 100644 --- a/stream/stream_test.go +++ b/stream/stream_test.go @@ -273,6 +273,24 @@ func TestStream_FindFirst(t *testing.T) { assert.Equal(true, ok) } +func TestStream_FindLast(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_FindLast") + + stream := FromSlice([]int{3, 2, 1}) + + result, ok := stream.FindLast() + + assert.Equal(1, result) + assert.Equal(true, ok) + + stream2 := FromSlice([]int{}) + + result, ok = stream2.FindLast() + + assert.Equal(0, result) + assert.Equal(false, ok) +} + func TestStream_Reverse(t *testing.T) { assert := internal.NewAssert(t, "TestStream_Reverse")