mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(package): [stream] do not call less with a zero value in Max and Min (#422)
* fix(package): [stream] do not call less with a zero value in Max and Min * test(package): [stream] cover Max and Min with pointer items
This commit is contained in:
1 parent
9c56f5f525
commit
afc0d3c676
2 files changed
+19
-2
No files matched your search
+2
-2
@@ -373,7 +373,7 @@ func (s Stream[T]) Max(less func(a, b T) bool) (T, bool) {
|
||||
}
|
||||
|
||||
for i, v := range s.source {
|
||||
if less(v, max) || i == 0 {
|
||||
if i == 0 || less(v, max) {
|
||||
max = v
|
||||
}
|
||||
}
|
||||
@@ -391,7 +391,7 @@ func (s Stream[T]) Min(less func(a, b T) bool) (T, bool) {
|
||||
}
|
||||
|
||||
for i, v := range s.source {
|
||||
if less(v, min) || i == 0 {
|
||||
if i == 0 || less(v, min) {
|
||||
min = v
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,3 +423,20 @@ func TestStream_ToMap(t *testing.T) {
|
||||
assert.EqualValues(expected, m)
|
||||
|
||||
}
|
||||
|
||||
func TestStream_MaxMinDoNotCompareWithZeroValue(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestStream_MaxMinDoNotCompareWithZeroValue")
|
||||
|
||||
type Person struct {
|
||||
Age int
|
||||
}
|
||||
s := FromSlice([]*Person{{Age: 20}, {Age: 10}, {Age: 30}})
|
||||
|
||||
max, ok := s.Max(func(a, b *Person) bool { return a.Age > b.Age })
|
||||
assert.Equal(true, ok)
|
||||
assert.Equal(30, max.Age)
|
||||
|
||||
min, ok := s.Min(func(a, b *Person) bool { return a.Age < b.Age })
|
||||
assert.Equal(true, ok)
|
||||
assert.Equal(10, min.Age)
|
||||
}
|
||||
Reference in new issue
Block a user