mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-09 15:12:26 +08:00
feat: add FromChannel for create stream
This commit is contained in:
@@ -57,8 +57,8 @@ func Of[T any](elems ...T) stream[T] {
|
||||
}
|
||||
|
||||
// Generate stream where each element is generated by the provided generater function
|
||||
// generater function: func(args ...U) func() (item T, ok bool) {}
|
||||
func Generate[T any](generator func() func() (T, bool)) stream[T] {
|
||||
// generater function: func() func() (item T, ok bool) {}
|
||||
func Generate[T any](generator func() func() (item T, ok bool)) stream[T] {
|
||||
source := make([]T, 0)
|
||||
|
||||
var zeroValue T
|
||||
@@ -77,6 +77,17 @@ func FromSlice[T any](source []T) stream[T] {
|
||||
return stream[T]{source: source}
|
||||
}
|
||||
|
||||
// FromChannel create stream from channel.
|
||||
func FromChannel[T any](source <-chan T) stream[T] {
|
||||
s := make([]T, 0)
|
||||
|
||||
for v := range source {
|
||||
s = append(s, v)
|
||||
}
|
||||
|
||||
return FromSlice(s)
|
||||
}
|
||||
|
||||
// FromRange create a number stream from start to end. both start and end are included. [start, end]
|
||||
func FromRange[T constraints.Integer | constraints.Float](start, end, step T) stream[T] {
|
||||
if end < start {
|
||||
@@ -92,7 +103,7 @@ func FromRange[T constraints.Integer | constraints.Float](start, end, step T) st
|
||||
source[i] = start + (T(i) * step)
|
||||
}
|
||||
|
||||
return stream[T]{source: source}
|
||||
return FromSlice(source)
|
||||
}
|
||||
|
||||
// Distinct returns a stream that removes the duplicated items.
|
||||
|
||||
Reference in New Issue
Block a user