proposal-math-clamp
v0.1.0
Published
ECMAScript reference implementation for `Math.clamp`.
Downloads
3
Readme
Math.clamp
ECMAScript proposal and reference implementation for Math.clamp
.
Author: Richie Bendall
Champion: None
Stage: 0
Overview and motivation
A clamping function constrains a value between an upper and lower bound.
The primary motivation for this function is to bring parity with the CSS function of the same name. It will be useful when using it in conjunction with the CSS Painting API.
Examples
Currently the problem is solved in two ways:
- Chaining mathematical operators with if statements or ternary operators
function clamp(number, minimum, maximum) {
if (number < minimum) {
return minimum;
}
if (number > maximum) {
return maximum;
}
return number;
}
function clamp(number, minimum, maximum) {
return Math.min(Math.max(number, minimum), maximum);
}
Each of these require a unnecessary boilerplate and are error-prone.
For example, a developer only has to mistype a single operator or mix up a single variable name for the function to break.
Both of these common strategies also disregard the potential undefined behaviour that can occur when minimum
is larger than maximum
.
The proposed API allows a developer to clamp numbers without creating a separate function:
Math.clamp(5, 0, 10);
//=> 5
Math.clamp(-5, 0, 10);
//=> 0
Math.clamp(15, 0, 10);
//=> 10
It also gracefully catches undefined behavior:
// Minimum number is larger than maximum value
Math.clamp(5, 10, 0);
//=> RangeError: The minimum value cannot be higher than the maximum value
Real-world scenarios
A common use is for animations and interactive content.
For example, it helps to keep objects in-bounds during user-controlled movement by restricting the coordinates that it can move to.
See the p5.js demo for its constrain
function.
Userland implementations
Naming in other languages
Similar functionality exists in other languages with most using a similar name. This is why the function will also be called clamp
.
clamp
in CSSMath.Clamp
in C#std::clamp
in the C++ standard libraryclamp
forf32
andf64
in RustcoerceIn
in Kotlinclamp
in Dartclamp
in Rubyclamp
in Elm
Specification
Implementations
Credits
- Specification improved from the
Math
Extensions Proposal - Specification and reference implementation further inspired by
math-clamp