Interfaces are full of number rules: a volume slider stays between 0 and 100, a carousel index wraps inside the number of slides, a rating badge shows the average score. Three small helpers cover most of them, and each has an edge that is easy to miss: bounds given in the wrong order, NaN from a bad input, an empty list.
Write three functions in math.js: clamp, inRange and mean.
clamp returns number when it is between lower and upper (both included), lower when it is below, and upper when it is above. It works when lower equals upper and with infinite bounds.
clamp throws a RangeError when lower is greater than upper. This check comes first: clamp(NaN, 2, 1) throws too.
Otherwise, clamp returns NaN when any argument is NaN. A NaN bound never counts as greater than the other bound, so it gives NaN, not an error.
inRange is true when number is at least start and less than end: start is included, end is not.
With two arguments, inRange(number, end) uses the range from 0 to end.
When start is greater than end (also after rule 5), inRange swaps them first.
inRange is false for an empty range and for NaN.
mean returns the sum of the numbers divided by their count, without rounding, and NaN for an empty array. It does not change the array.