From a1943556b41d584fcf5cec89ce7cb31ed4f97316 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Fri, 14 Nov 2025 13:51:35 +0100 Subject: [PATCH] fix: add explicit panic for Max/Min on empty slices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- max.go | 4 ++++ max_test.go | 6 ++++++ min.go | 4 ++++ min_test.go | 6 ++++++ 4 files changed, 20 insertions(+) diff --git a/max.go b/max.go index be74b3c..31957d0 100644 --- a/max.go +++ b/max.go @@ -3,9 +3,13 @@ package underscore import "cmp" // Max returns the maximum value in the slice. +// Panics if values is empty. // This function can currently only compare numbers reliably. // This function uses operator <. func Max[T cmp.Ordered](values []T) T { + if len(values) == 0 { + panic("underscore.Max: empty slice") + } max := values[0] for _, v := range values { if v > max { diff --git a/max_test.go b/max_test.go index 5fed20a..1c05cd1 100644 --- a/max_test.go +++ b/max_test.go @@ -13,3 +13,9 @@ func TestMax(t *testing.T) { want := 9 assert.Equal(t, want, u.Max(nums)) } + +func TestMaxEmpty(t *testing.T) { + assert.Panics(t, func() { + u.Max([]int{}) + }) +} diff --git a/min.go b/min.go index 35c42a0..1e192c6 100644 --- a/min.go +++ b/min.go @@ -3,9 +3,13 @@ package underscore import "cmp" // Min returns the minimum value in the slice. +// Panics if values is empty. // This function can currently only compare numbers reliably. // This function uses operator <. func Min[T cmp.Ordered](values []T) T { + if len(values) == 0 { + panic("underscore.Min: empty slice") + } min := values[0] for _, v := range values { if v < min { diff --git a/min_test.go b/min_test.go index 2b4f6cc..8049bb4 100644 --- a/min_test.go +++ b/min_test.go @@ -13,3 +13,9 @@ func TestMin(t *testing.T) { want := 1 assert.Equal(t, want, u.Min(nums)) } + +func TestMinEmpty(t *testing.T) { + assert.Panics(t, func() { + u.Min([]int{}) + }) +}