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

feat: add Range for stream

This commit is contained in:
dudaodong
2023-02-07 10:36:07 +08:00
parent 87fcf97e2d
commit 422022c74d
2 changed files with 49 additions and 0 deletions

View File

@@ -277,6 +277,31 @@ func (s stream[T]) Reverse() stream[T] {
return FromSlice(source)
}
// Range returns a stream whose elements are in the range from start(included) to end(excluded) original stream.
func (s stream[T]) Range(start, end int) stream[T] {
if start < 0 {
start = 0
}
if end < 0 {
end = 0
}
if start >= end {
return FromSlice([]T{})
}
source := make([]T, 0)
if end > len(s.source) {
end = len(s.source)
}
for i := start; i < end; i++ {
source = append(source, s.source[i])
}
return FromSlice(source)
}
// ToSlice return the elements in the stream.
func (s stream[T]) ToSlice() []T {
return s.source

View File

@@ -268,3 +268,27 @@ func TestStream_Reverse(t *testing.T) {
assert.Equal([]int{3, 2, 1}, rs.ToSlice())
}
func TestStream_Range(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Range")
s := FromSlice([]int{1, 2, 3})
s1 := s.Range(-1, 0)
assert.Equal([]int{}, s1.ToSlice())
s2 := s.Range(0, -1)
assert.Equal([]int{}, s2.ToSlice())
s3 := s.Range(0, 0)
assert.Equal([]int{}, s3.ToSlice())
s4 := s.Range(1, 1)
assert.Equal([]int{}, s4.ToSlice())
s5 := s.Range(0, 1)
assert.Equal([]int{1}, s5.ToSlice())
s6 := s.Range(0, 4)
assert.Equal([]int{1, 2, 3}, s6.ToSlice())
}