github.com/enetx/g@v1.0.80/cmp/maxmin.go (about) 1 package cmp 2 3 import "cmp" 4 5 // Min returns the minimum value among the given values. The values must be of a type that implements 6 // the cmp.Ordered interface for comparison. 7 func Min[T cmp.Ordered](t ...T) T { return MinBy(Cmp, t...) } 8 9 // Max returns the maximum value among the given values. The values must be of a type that implements 10 // the cmp.Ordered interface for comparison. 11 func Max[T cmp.Ordered](t ...T) T { return MaxBy(Cmp, t...) } 12 13 // MinBy finds the minimum value in the collection t according to the provided comparison function fn. 14 // It returns the minimum value found. 15 func MinBy[T any](fn func(x, y T) Ordering, t ...T) T { 16 if len(t) == 0 { 17 return *new(T) 18 } 19 20 m := t[0] 21 22 for _, v := range t[1:] { 23 if fn(v, m).IsLt() { 24 m = v 25 } 26 } 27 28 return m 29 } 30 31 // MaxBy finds the maximum value in the collection t according to the provided comparison function fn. 32 // It returns the maximum value found. 33 func MaxBy[T any](fn func(x, y T) Ordering, t ...T) T { 34 if len(t) == 0 { 35 return *new(T) 36 } 37 38 m := t[0] 39 40 for _, v := range t[1:] { 41 if fn(v, m).IsGt() { 42 m = v 43 } 44 } 45 46 return m 47 }