1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add Concat for stream

This commit is contained in:
dudaodong
2023-02-07 10:47:28 +08:00
parent 422022c74d
commit 6bba44dc50
2 changed files with 24 additions and 3 deletions

View File

@@ -72,12 +72,12 @@ func Generate[T any](generator func() func() (item T, ok bool)) stream[T] {
return FromSlice(source)
}
// FromSlice create stream from slice.
// FromSlice creates stream from slice.
func FromSlice[T any](source []T) stream[T] {
return stream[T]{source: source}
}
// FromChannel create stream from channel.
// FromChannel creates stream from channel.
func FromChannel[T any](source <-chan T) stream[T] {
s := make([]T, 0)
@@ -88,7 +88,7 @@ func FromChannel[T any](source <-chan T) stream[T] {
return FromSlice(s)
}
// FromRange create a number stream from start to end. both start and end are included. [start, end]
// FromRange creates 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 {
panic("stream.FromRange: param start should be before param end")
@@ -106,6 +106,16 @@ func FromRange[T constraints.Integer | constraints.Float](start, end, step T) st
return FromSlice(source)
}
// Concat creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
func Concat[T any](a, b stream[T]) stream[T] {
source := make([]T, 0)
source = append(source, a.source...)
source = append(source, b.source...)
return FromSlice(source)
}
// Distinct returns a stream that removes the duplicated items.
func (s stream[T]) Distinct() stream[T] {
source := make([]T, 0)

View File

@@ -292,3 +292,14 @@ func TestStream_Range(t *testing.T) {
s6 := s.Range(0, 4)
assert.Equal([]int{1, 2, 3}, s6.ToSlice())
}
func TestStream_Concat(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Concat")
s1 := FromSlice([]int{1, 2, 3})
s2 := FromSlice([]int{4, 5, 6})
s := Concat(s1, s2)
assert.Equal([]int{1, 2, 3, 4, 5, 6}, s.ToSlice())
}