mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-12 16:52:29 +08:00
feat: add Generate for create stream
This commit is contained in:
@@ -56,6 +56,22 @@ func Of[T any](elems ...T) stream[T] {
|
||||
return FromSlice(elems)
|
||||
}
|
||||
|
||||
// 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] {
|
||||
source := make([]T, 0)
|
||||
|
||||
var zeroValue T
|
||||
for next, item, ok := generator(), zeroValue, true; ok; {
|
||||
item, ok = next()
|
||||
if ok {
|
||||
source = append(source, item)
|
||||
}
|
||||
}
|
||||
|
||||
return FromSlice(source)
|
||||
}
|
||||
|
||||
// FromSlice create stream from slice.
|
||||
func FromSlice[T any](source []T) stream[T] {
|
||||
return stream[T]{source: source}
|
||||
|
||||
Reference in New Issue
Block a user