From b28699cd316e339c86e1f0a4751ed7021db3c787 Mon Sep 17 00:00:00 2001 From: Adrian Dewhurst Date: Tue, 19 Aug 2025 12:05:41 -0400 Subject: [PATCH] types/views: add min/max helpers to views.Slice This has come up in a few situations recently and adding these helpers is much better than copying the slice (calling AsSlice()) in order to use slices.Max and friends. Updates #cleanup Change-Id: Ib289a07d23c3687220c72c4ce341b9695cd875bf Signed-off-by: Adrian Dewhurst --- types/views/views.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/types/views/views.go b/types/views/views.go index 6d15b80d4..252f126a7 100644 --- a/types/views/views.go +++ b/types/views/views.go @@ -7,6 +7,7 @@ package views import ( "bytes" + "cmp" jsonv1 "encoding/json" "errors" "fmt" @@ -363,6 +364,20 @@ func (v Slice[T]) ContainsFunc(f func(T) bool) bool { return slices.ContainsFunc(v.ж, f) } +// MaxFunc returns the maximal value in v, using cmp to compare elements. It +// panics if v is empty. If there is more than one maximal element according to +// the cmp function, MaxFunc returns the first one. See also [slices.MaxFunc]. +func (v Slice[T]) MaxFunc(cmp func(a, b T) int) T { + return slices.MaxFunc(v.ж, cmp) +} + +// MinFunc returns the minimal value in v, using cmp to compare elements. It +// panics if v is empty. If there is more than one minimal element according to +// the cmp function, MinFunc returns the first one. See also [slices.MinFunc]. +func (v Slice[T]) MinFunc(cmp func(a, b T) int) T { + return slices.MinFunc(v.ж, cmp) +} + // AppendStrings appends the string representation of each element in v to dst. func AppendStrings[T fmt.Stringer](dst []string, v Slice[T]) []string { for _, x := range v.ж { @@ -383,6 +398,20 @@ func SliceEqual[T comparable](a, b Slice[T]) bool { return slices.Equal(a.ж, b.ж) } +// SliceMax returns the maximal value in v. It panics if v is empty. For +// floating point T, SliceMax propagates NaNs (any NaN value in v forces the +// output to be NaN). See also [slices.Max]. +func SliceMax[T cmp.Ordered](v Slice[T]) T { + return slices.Max(v.ж) +} + +// SliceMin returns the minimal value in v. It panics if v is empty. For +// floating point T, SliceMin propagates NaNs (any NaN value in v forces the +// output to be NaN). See also [slices.Min]. +func SliceMin[T cmp.Ordered](v Slice[T]) T { + return slices.Min(v.ж) +} + // shortOOOLen (short Out-of-Order length) is the slice length at or // under which we attempt to compare two slices quadratically rather // than allocating memory for a map in SliceEqualAnyOrder and