feat: add Generate for create stream

This commit is contained in:
dudaodong committed 2023-01-17 16:31:44 +08:00
1 parent bc4cf35e15
commit 585d33cafa
2 files changed
+41

No files matched your search

+16
View File
@@ -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}