From b26a360495099c1bd9fa8d5a6c4e675d0105bd0e Mon Sep 17 00:00:00 2001 From: Ruidy Date: Wed, 29 Dec 2021 22:35:39 -0400 Subject: [PATCH] feat: min --- README.md | 1 + max.go | 3 +++ min.go | 14 ++++++++++++++ min_test.go | 15 +++++++++++++++ 4 files changed, 33 insertions(+) create mode 100644 min.go create mode 100644 min_test.go diff --git a/README.md b/README.md index 0627ad1..24e4ce3 100644 --- a/README.md +++ b/README.md @@ -20,3 +20,4 @@ It is mostly a port from the `underscore.js` library based on generics brought b - `find` - `contains` (only numerics values at the moment) - `max` +- `min` diff --git a/max.go b/max.go index 9821e82..440cbbe 100644 --- a/max.go +++ b/max.go @@ -1,5 +1,8 @@ package underscore +// Max returns the maximum value in the slice. +// This function can currently only compare numbers reliably. +// This function uses operator <. func Max[T numbers](values []T) T { max := values[0] for _, v := range values { diff --git a/min.go b/min.go new file mode 100644 index 0000000..a2883ea --- /dev/null +++ b/min.go @@ -0,0 +1,14 @@ +package underscore + +// Min returns the minimum value in the slice. +// This function can currently only compare numbers reliably. +// This function uses operator <. +func Min[T numbers](values []T) T { + min := values[0] + for _, v := range values { + if v < min { + min = v + } + } + return min +} diff --git a/min_test.go b/min_test.go new file mode 100644 index 0000000..ab66847 --- /dev/null +++ b/min_test.go @@ -0,0 +1,15 @@ +package underscore_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + u "github.com/rjNemo/underscore" +) + +func TestMin(t *testing.T) { + nums := []int{1, 9, 2, 8, 3, 7, 4, 6, 5} + want := 1 + assert.Equal(t, want, u.Min(nums)) +}