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

feat:addFindLast for stream (#95)

Co-authored-by: sunyaoyao <sunyaoyao@kezaihui.com>
This commit is contained in:
will
2023-05-18 10:17:15 +08:00
committed by GitHub
parent aa8e0d5c12
commit 1616d3d1be
3 changed files with 43 additions and 0 deletions

View File

@@ -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] {

View File

@@ -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})

View File

@@ -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")