ECMAScript reference implementation for `Math.clamp`.
npm install proposal-math-clampMath.clampMath.clamp.
js
function clamp(number, minimum, maximum) {
if (number < minimum) {
return minimum;
}
if (number > maximum) {
return maximum;
}
return number;
}
`
- Nesting [Math.min][math-min] and [Math.max][math-max] calls
`js
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:
`js
Math.clamp(5, 0, 10);
//=> 5
Math.clamp(-5, 0, 10);
//=> 0
Math.clamp(15, 0, 10);
//=> 10
`
It also gracefully catches undefined behavior:
`js
// Minimum number is larger than maximum value
Math.clamp(5, 10, 0);
//=> RangeError: The minimum value cannot be higher than the maximum value
`
$3
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
- clamp
- [math-clamp][math-clamp]
- lodash
- three.js
- p5.js
- ramda
- sugar
- phaser
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][css-clamp] in CSS
- Math.Clamp in C#
- std::clamp in the C++ standard library
- clamp for f32 and f64 in Rust
- coerceIn in Kotlin
- clamp in Dart
- clamp in Ruby
- clamp in Elm
Specification
- Ecmarkup source
- HTML version
Implementations
- Polyfill
Credits
- Specification improved from the Math Extensions Proposal
- Specification and reference implementation further inspired by [math-clamp`][math-clamp]