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

feat: add NoneMatch, AllMatch, AnyMatch for stream

This commit is contained in:
dudaodong
2023-02-06 17:24:17 +08:00
parent 48c7794b01
commit b4b9b03835
2 changed files with 80 additions and 1 deletions

View File

@@ -167,7 +167,8 @@ func (s stream[T]) Peek(consumer func(item T)) stream[T] {
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.
// 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
@@ -206,6 +207,33 @@ func (s stream[T]) Limit(maxSize int) stream[T] {
return FromSlice(source)
}
// AllMatch returns whether all elements of this stream match the provided predicate.
func (s stream[T]) AllMatch(predicate func(item T) bool) bool {
for _, v := range s.source {
if !predicate(v) {
return false
}
}
return true
}
// AnyMatch returns whether any elements of this stream match the provided predicate.
func (s stream[T]) AnyMatch(predicate func(item T) bool) bool {
for _, v := range s.source {
if predicate(v) {
return true
}
}
return false
}
// NoneMatch returns whether no elements of this stream match the provided predicate.
func (s stream[T]) NoneMatch(predicate func(item T) bool) bool {
return !s.AnyMatch(predicate)
}
// Count returns the count of elements in the stream.
func (s stream[T]) Count() int {
return len(s.source)

View File

@@ -171,3 +171,54 @@ func TestStream_Limit(t *testing.T) {
assert.Equal([]int{1}, s3.ToSlice())
assert.Equal([]int{1, 2, 3, 4, 5, 6}, s4.ToSlice())
}
func TestStream_AllMatch(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_AllMatch")
stream := FromSlice([]int{1, 2, 3, 4, 5, 6})
result1 := stream.AllMatch(func(item int) bool {
return item > 0
})
result2 := stream.AllMatch(func(item int) bool {
return item > 1
})
assert.Equal(true, result1)
assert.Equal(false, result2)
}
func TestStream_AnyMatch(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_AnyMatch")
stream := FromSlice([]int{1, 2, 3})
result1 := stream.AnyMatch(func(item int) bool {
return item > 3
})
result2 := stream.AnyMatch(func(item int) bool {
return item > 1
})
assert.Equal(false, result1)
assert.Equal(true, result2)
}
func TestStream_NoneMatch(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_NoneMatch")
stream := FromSlice([]int{1, 2, 3})
result1 := stream.NoneMatch(func(item int) bool {
return item > 3
})
result2 := stream.NoneMatch(func(item int) bool {
return item > 1
})
assert.Equal(true, result1)
assert.Equal(false, result2)
}