clamp<T extends num> function

T clamp<T extends num>(
  1. T v,
  2. T lo,
  3. T hi
)

Clamps v between lo and hi.

Returns lo if v is less than lo, returns hi if v is greater than hi, and returns v otherwise. Corresponds to std::clamp from C++17.

Implementation

T clamp<T extends num>(T v, T lo, T hi) {
  if (lo > hi) {
    throw ArgumentError('lo ($lo) cannot be greater than hi ($hi)');
  }
  if (v < lo) return lo;
  if (v > hi) return hi;
  return v;
}