What's the most elegant way to cap a number to a segment?

Samuel Rossille picture Samuel Rossille · Jul 10, 2012 · Viewed 116.5k times · Source

Let's say x, a and b are numbers. I need to cap x to the bounds of the segment [a, b].

I can write Math.max(a, Math.min(x, b)), but i don't think it's very easy to read. Does anybody has a clever way to write this in a more readable way?

Answer

Otto Allmendinger picture Otto Allmendinger · Jul 10, 2012

The way you do it is pretty standard. You can define a utility clamp function:

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};

(Although extending language built-ins is generally frowned upon)