func MinBy[T any](collection []T, comparison func(T, T) bool) T {
var min T
if len(collection) == 0 {
return min
}
min = collection[0]
for i := 1; i < len(collection); i++ {
item := collection[i]
if comparison(item, min) {
min = item
}
}
return min
}
func MaxBy[T any](collection []T, comparison func(T, T) bool) T {
var max T
if len(collection) == 0 {
return max
}
max = collection[0]
for i := 1; i < len(collection); i++ {
item := collection[i]
if comparison(item, max) {
max = item
}
}
return max
}
comparison in MinBy is less,while in MaxBy is greater. In most of the generics library, just need one comparison function, less, such as C++ STL. This minimizes user misuse.
comparison in MinBy is
less,while in MaxBy isgreater. In most of the generics library, just need one comparison function, less, such as C++ STL. This minimizes user misuse.