mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +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.
|
||||
|
||||
@@ -39,6 +39,22 @@ func TestFromSlice(t *testing.T) {
|
||||
assert.Equal([]int{1, 2, 3}, stream.ToSlice())
|
||||
}
|
||||
|
||||
func TestFromChannel(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestFromChannel")
|
||||
|
||||
ch := make(chan int)
|
||||
go func() {
|
||||
for i := 1; i < 4; i++ {
|
||||
ch <- i
|
||||
}
|
||||
close(ch)
|
||||
}()
|
||||
|
||||
stream := FromChannel(ch)
|
||||
|
||||
assert.Equal([]int{1, 2, 3}, stream.ToSlice())
|
||||
}
|
||||
|
||||
func TestFromRange(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestFromRange")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user