From ea0f96a8c0ca38bdfefefc37b06673c0b33bdcda Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 30 Jan 2023 16:56:33 +0800 Subject: [PATCH] feat: add Skip for stream --- stream/stream.go | 33 ++++++++++++++++++++++++++++++++- stream/stream_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/stream/stream.go b/stream/stream.go index 4ac92b4..c694aaa 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -28,7 +28,7 @@ import ( // Min(less func(a, b T) bool) (T, bool) // Limit(maxSize int) StreamI[T] -// Skip(n int64) StreamI[T] +// Skip(n int) StreamI[T] // AllMatch(predicate func(item T) bool) bool // AnyMatch(predicate func(item T) bool) bool @@ -158,6 +158,37 @@ func (s stream[T]) Map(mapper func(item T) T) stream[T] { return FromSlice(source) } +// Peek returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. +func (s stream[T]) Peek(consumer func(item T)) stream[T] { + for _, v := range s.source { + consumer(v) + } + + return s +} + +// Skip Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned. +func (s stream[T]) Skip(n int) stream[T] { + if n <= 0 { + return s + } + + source := make([]T, 0) + l := len(s.source) + + if n > l { + return FromSlice(source) + } + + // source = make([]T, l-n+1, l-n+1) + + for i := n; i < l; i++ { + source = append(source, s.source[i]) + } + + return FromSlice(source) +} + // Count returns the count of elements in the stream. func (s stream[T]) Count() int { return len(s.source) diff --git a/stream/stream_test.go b/stream/stream_test.go index 271e46f..4fb5e38 100644 --- a/stream/stream_test.go +++ b/stream/stream_test.go @@ -1,6 +1,7 @@ package stream import ( + "fmt" "testing" "github.com/duke-git/lancet/v2/internal" @@ -124,3 +125,34 @@ func TestStream_Map(t *testing.T) { assert.Equal([]int{2, 3, 4}, s.ToSlice()) } + +func TestStream_Peek(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_Peek") + + stream := FromSlice([]int{1, 2, 3, 4, 5, 6}) + + result := []string{} + stream = stream.Filter(func(n int) bool { + return n <= 3 + }).Peek(func(n int) { + result = append(result, fmt.Sprint("current: ", n)) + }) + + assert.Equal([]int{1, 2, 3}, stream.ToSlice()) + assert.Equal([]string{ + "current: 1", "current: 2", "current: 3", + }, result) +} + +func TestStream_Skip(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_Peek") + + stream := FromSlice([]int{1, 2, 3, 4, 5, 6}) + + s1 := stream.Skip(-1) + s2 := stream.Skip(0) + // s2 := stream.Skip(0) + + assert.Equal([]int{1, 2, 3, 4, 5, 6}, s1.ToSlice()) + assert.Equal([]int{1, 2, 3, 4, 5, 6}, s2.ToSlice()) +}