1
0
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:
dudaodong
2023-01-17 16:31:44 +08:00
parent bc4cf35e15
commit 585d33cafa
2 changed files with 41 additions and 0 deletions

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}