}
// MinFunc returns the minimal value in x, using cmp to compare elements.
-// It panics if x is empty.
+// It panics if x is empty. If there is more than one minimal element
+// according to the cmp function, MinFunc returns the first one.
func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
if len(x) < 1 {
panic("slices.MinFunc: empty list")
}
// MaxFunc returns the maximal value in x, using cmp to compare elements.
-// It panics if x is empty.
+// It panics if x is empty. If there is more than one maximal element
+// according to the cmp function, MaxFunc returns the first one.
func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
if len(x) < 1 {
panic("slices.MaxFunc: empty list")
}
}
+type S struct {
+ a int
+ b string
+}
+
+func cmpS(s1, s2 S) int {
+ return cmp.Compare(s1.a, s2.a)
+}
+
func TestMinMax(t *testing.T) {
intCmp := func(a, b int) int { return a - b }
}
})
}
+
+ svals := []S{
+ {1, "a"},
+ {2, "a"},
+ {1, "b"},
+ {2, "b"},
+ }
+
+ gotMin := MinFunc(svals, cmpS)
+ wantMin := S{1, "a"}
+ if gotMin != wantMin {
+ t.Errorf("MinFunc(%v) = %v, want %v", svals, gotMin, wantMin)
+ }
+
+ gotMax := MaxFunc(svals, cmpS)
+ wantMax := S{2, "a"}
+ if gotMax != wantMax {
+ t.Errorf("MaxFunc(%v) = %v, want %v", svals, gotMax, wantMax)
+ }
}
func TestMinMaxNaNs(t *testing.T) {