fix: add explicit panic for Max/Min on empty slices

Adds length checks to Max and Min functions to provide clear,
explicit panic messages when called with empty slices, rather
than allowing confusing index-out-of-bounds panics.

Changes:
- Max: Added check for empty slice with "underscore.Max: empty slice" panic
- Min: Added check for empty slice with "underscore.Min: empty slice" panic
- Updated doc comments to document panic behavior
- Added TestMaxEmpty and TestMinEmpty to verify panic behavior

Impact:
- Better error messages for debugging
- Documented behavior prevents user surprises
- Non-breaking change (still panics, just with clearer message)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Ruidy 2025-11-14 13:51:35 +01:00
parent 46d52e3cfa
commit a1943556b4
No known key found for this signature in database
GPG key ID: 705C24D202990805
4 changed files with 20 additions and 0 deletions

4
max.go
View file

@ -3,9 +3,13 @@ package underscore
import "cmp" import "cmp"
// Max returns the maximum value in the slice. // Max returns the maximum value in the slice.
// Panics if values is empty.
// This function can currently only compare numbers reliably. // This function can currently only compare numbers reliably.
// This function uses operator <. // This function uses operator <.
func Max[T cmp.Ordered](values []T) T { func Max[T cmp.Ordered](values []T) T {
if len(values) == 0 {
panic("underscore.Max: empty slice")
}
max := values[0] max := values[0]
for _, v := range values { for _, v := range values {
if v > max { if v > max {

View file

@ -13,3 +13,9 @@ func TestMax(t *testing.T) {
want := 9 want := 9
assert.Equal(t, want, u.Max(nums)) assert.Equal(t, want, u.Max(nums))
} }
func TestMaxEmpty(t *testing.T) {
assert.Panics(t, func() {
u.Max([]int{})
})
}

4
min.go
View file

@ -3,9 +3,13 @@ package underscore
import "cmp" import "cmp"
// Min returns the minimum value in the slice. // Min returns the minimum value in the slice.
// Panics if values is empty.
// This function can currently only compare numbers reliably. // This function can currently only compare numbers reliably.
// This function uses operator <. // This function uses operator <.
func Min[T cmp.Ordered](values []T) T { func Min[T cmp.Ordered](values []T) T {
if len(values) == 0 {
panic("underscore.Min: empty slice")
}
min := values[0] min := values[0]
for _, v := range values { for _, v := range values {
if v < min { if v < min {

View file

@ -13,3 +13,9 @@ func TestMin(t *testing.T) {
want := 1 want := 1
assert.Equal(t, want, u.Min(nums)) assert.Equal(t, want, u.Min(nums))
} }
func TestMinEmpty(t *testing.T) {
assert.Panics(t, func() {
u.Min([]int{})
})
}