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

feat: add FindFirst, Reverse for stream

This commit is contained in:
dudaodong
2023-02-07 10:24:19 +08:00
parent 05d1f348d4
commit 87fcf97e2d
2 changed files with 44 additions and 1 deletions

View File

@@ -43,7 +43,7 @@ import (
// // part of methods custom extension
// Reverse() StreamI[T]
// Range(start, end int64) StreamI[T]
// Range(start, end int) StreamI[T]
// Concat(streams ...StreamI[T]) StreamI[T]
// }
@@ -255,6 +255,28 @@ func (s stream[T]) Count() int {
return len(s.source)
}
// FindFirst returns the first element of this stream and true, or zero value and false if the stream is empty.
func (s stream[T]) FindFirst() (T, bool) {
var result T
if s.source == nil || len(s.source) == 0 {
return result, false
}
return s.source[0], true
}
// Reverse returns a stream whose elements are reverse order of given stream.
func (s stream[T]) Reverse() stream[T] {
l := len(s.source)
source := make([]T, l)
for i := 0; i < l; i++ {
source[i] = s.source[l-1-i]
}
return FromSlice(source)
}
// ToSlice return the elements in the stream.
func (s stream[T]) ToSlice() []T {
return s.source

View File

@@ -247,3 +247,24 @@ func TestStream_Reduce(t *testing.T) {
assert.Equal(6, result)
}
func TestStream_FindFirst(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_FindFirst")
stream := FromSlice([]int{1, 2, 3})
result, ok := stream.FindFirst()
assert.Equal(1, result)
assert.Equal(true, ok)
}
func TestStream_Reverse(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Reverse")
s := FromSlice([]int{1, 2, 3})
rs := s.Reverse()
assert.Equal([]int{3, 2, 1}, rs.ToSlice())
}