diff --git a/koboldsim/util.go b/koboldsim/util.go index 7251fb3..0e36564 100644 --- a/koboldsim/util.go +++ b/koboldsim/util.go @@ -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 }