1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-16 10:42:27 +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