Debian Codegraph @

exp/ordered/ordered.go

raw
1 // Package ordered provides utility functions for ordered types.
2 package ordered
3
4 import "cmp"
5
6 // Min returns the smaller of a and b.
7 func Min[T cmp.Ordered](a, b T) T {
8 if a < b {
9 return a
10 }
11 return b
12 }
13
14 // Max returns the larger of a and b.
15 func Max[T cmp.Ordered](a, b T) T {
16 if a > b {
17 return a
18 }
19 return b
20 }
21
22 // Clamp returns a value clamped between the given low and high values.
23 func Clamp[T cmp.Ordered](n, low, high T) T {
24 if low > high {
25 low, high = high, low
26 }
27 return Min(high, Max(low, n))
28 }
29
30 // First returns the first non-default value of a fixed number of
31 // arguments of [cmp.Ordered] types.
32 func First[T cmp.Ordered](x T, y ...T) T {
33 var empty T
34 if x != empty {
35 return x
36 }
37 for _, s := range y {
38 if s != empty {
39 return s
40 }
41 }
42 return empty
43 }