-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcmp.go
66 lines (56 loc) · 1.18 KB
/
cmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package fun
import "cmp"
// Min returns the minimum of the given values
func Min[T cmp.Ordered](xs ...T) T {
if len(xs) == 0 {
return Zero[T]()
}
res := xs[0]
for _, x := range xs[1:] {
res = min(res, x)
}
return res
}
// Max returns the maximum of the given values
func Max[T cmp.Ordered](xs ...T) T {
if len(xs) == 0 {
return Zero[T]()
}
res := xs[0]
for _, x := range xs[1:] {
res = max(res, x)
}
return res
}
// Clamp returns x clamped between low and high
func Clamp[T cmp.Ordered](x, low, high T) T {
return max(low, min(x, high))
}
// MinBy returns the minimum of the given values using the given order function
func MinBy[T any, R cmp.Ordered](order func(T) R, xs ...T) T {
if len(xs) == 0 {
return Zero[T]()
}
res := xs[0]
fres := order(res)
for _, x := range xs[1:] {
if fx := order(x); fres > fx {
res, fres = x, fx
}
}
return res
}
// MaxBy returns the maximum of the given values using the given order function
func MaxBy[T any, R cmp.Ordered](order func(T) R, xs ...T) T {
if len(xs) == 0 {
return Zero[T]()
}
res := xs[0]
fres := order(res)
for _, x := range xs[1:] {
if fx := order(x); fres < fx {
res, fres = x, fx
}
}
return res
}