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))
|
return total / float64(len(vals))
|
||||||
}
|
}
|
||||||
|
|
||||||
func clamp[T constraints.Ordered](val, low, high T) T {
|
// clamp returns the middle of the three provided values. It doesn't
|
||||||
if val < low {
|
// matter which order the values are in. This function is known as `mid` in
|
||||||
return low
|
// 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
|
||||||
}
|
}
|
||||||
if val > high {
|
return c
|
||||||
return high
|
|
||||||
}
|
}
|
||||||
return val
|
if a >= b && a >= c {
|
||||||
|
// `a` is most; mid is greater of `b` or `c`
|
||||||
|
if b >= c {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
// `a` is neither most nor least; therefore, `a` is mid
|
||||||
|
return a
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user