proposal-math-clamp

0.1.0 • Public • Published

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.

Specification

Implementations

Credits

Readme

Keywords

Package Sidebar

Install

npm i proposal-math-clamp

Weekly Downloads

1

Version

0.1.0

License

BSD-3-Clause

Unpacked Size

6.44 kB

Total Files

5

Last publish

Collaborators

  • richienb