reimplement clamp as mid
removes an opportunity to write a bug by swapping low and high
This commit is contained in:
parent
c4427885ca
commit
b2099586fc
@ -25,12 +25,25 @@ func Mean(vals ...float64) float64 {
|
||||
return total / float64(len(vals))
|
||||
}
|
||||
|
||||
func clamp[T constraints.Ordered](val, low, high T) T {
|
||||
if val < low {
|
||||
return low
|
||||
// clamp returns the middle of the three provided values. It doesn't
|
||||
// matter which order the values are in. This function is known as `mid` in
|
||||
// Pico-8's library, among others. It is usually used to clamp a value to a
|
||||
// range, and it doesn't care which order the range is written in.
|
||||
func clamp[T constraints.Ordered](a, b, c T) T {
|
||||
if a <= b && a <= c {
|
||||
// `a` is least; mid is lower of `b` or `c`
|
||||
if b <= c {
|
||||
return b
|
||||
}
|
||||
return c
|
||||
}
|
||||
if val > high {
|
||||
return high
|
||||
if a >= b && a >= c {
|
||||
// `a` is most; mid is greater of `b` or `c`
|
||||
if b >= c {
|
||||
return b
|
||||
}
|
||||
return c
|
||||
}
|
||||
return val
|
||||
// `a` is neither most nor least; therefore, `a` is mid
|
||||
return a
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user