1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-23 13:52:26 +08:00

Compare commits

...

2 Commits

Author SHA1 Message Date
dudaodong
afb021b4b5 feat: add Max, Min for stream 2023-02-08 15:20:29 +08:00
dudaodong
5075774000 feat: add Sorted for stream 2023-02-08 15:07:09 +08:00
2 changed files with 80 additions and 1 deletions

View File

@@ -10,6 +10,7 @@ import (
"bytes"
"encoding/gob"
"github.com/duke-git/lancet/v2/slice"
"golang.org/x/exp/constraints"
)
@@ -23,7 +24,7 @@ import (
// Map(mapper func(item T) T) StreamI[T]
// Peek(consumer func(item T)) StreamI[T]
// Sort(less func(a, b T) bool) StreamI[T]
// Sorted(less func(a, b T) bool) StreamI[T]
// Max(less func(a, b T) bool) (T, bool)
// Min(less func(a, b T) bool) (T, bool)
@@ -312,6 +313,51 @@ func (s stream[T]) Range(start, end int) stream[T] {
return FromSlice(source)
}
// Sorted returns a stream consisting of the elements of this stream, sorted according to the provided less function.
func (s stream[T]) Sorted(less func(a, b T) bool) stream[T] {
source := []T{}
source = append(source, s.source...)
slice.SortBy(source, less)
return FromSlice(source)
}
// Max returns the maximum element of this stream according to the provided less function.
// less: a > b
func (s stream[T]) Max(less func(a, b T) bool) (T, bool) {
var max T
if len(s.source) == 0 {
return max, false
}
for i, v := range s.source {
if less(v, max) || i == 0 {
max = v
}
}
return max, true
}
// Min returns the minimum element of this stream according to the provided less function.
// less: a < b
func (s stream[T]) Min(less func(a, b T) bool) (T, bool) {
var min T
if len(s.source) == 0 {
return min, false
}
for i, v := range s.source {
if less(v, min) || i == 0 {
min = v
}
}
return min, true
}
// ToSlice return the elements in the stream.
func (s stream[T]) ToSlice() []T {
return s.source

View File

@@ -303,3 +303,36 @@ func TestStream_Concat(t *testing.T) {
assert.Equal([]int{1, 2, 3, 4, 5, 6}, s.ToSlice())
}
func TestStream_Sorted(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Sorted")
s := FromSlice([]int{4, 2, 1, 3})
s1 := s.Sorted(func(a, b int) bool { return a < b })
assert.Equal([]int{4, 2, 1, 3}, s.ToSlice())
assert.Equal([]int{1, 2, 3, 4}, s1.ToSlice())
}
func TestStream_Max(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Max")
s := FromSlice([]int{4, 2, 1, 3})
max, ok := s.Max(func(a, b int) bool { return a > b })
assert.Equal(4, max)
assert.Equal(true, ok)
}
func TestStream_Min(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_Min")
s := FromSlice([]int{4, 2, 1, 3})
max, ok := s.Max(func(a, b int) bool { return a < b })
assert.Equal(1, max)
assert.Equal(true, ok)
}