From b2099586fc7cd7d6f0c641ad4a362b0febd1fa2b Mon Sep 17 00:00:00 2001 From: Kistaro Windrider Date: Sun, 29 Sep 2024 12:09:11 -0700 Subject: [PATCH] reimplement clamp as mid removes an opportunity to write a bug by swapping low and high --- koboldsim/util.go | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) 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 }