mirror of
https://github.com/duke-git/lancet.git
synced 2026-03-01 00:35:28 +08:00
feat: add Range for stream
This commit is contained in:
@@ -277,6 +277,31 @@ func (s stream[T]) Reverse() stream[T] {
|
|||||||
return FromSlice(source)
|
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.
|
// ToSlice return the elements in the stream.
|
||||||
func (s stream[T]) ToSlice() []T {
|
func (s stream[T]) ToSlice() []T {
|
||||||
return s.source
|
return s.source
|
||||||
|
|||||||
@@ -268,3 +268,27 @@ func TestStream_Reverse(t *testing.T) {
|
|||||||
|
|
||||||
assert.Equal([]int{3, 2, 1}, rs.ToSlice())
|
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())
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user