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

2019-01-16 09:24发布

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?

9条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-16 10:18

a less "Math" oriented approach ,but should also work , this way, the < / > test is exposed (maybe more understandable than minimaxing) but it really depends on what you mean by "readable"

function clamp(num, min, max) {
  return num <= min ? min : num >= max ? max : num;
}
查看更多
ら.Afraid
3楼-- · 2019-01-16 10:24

My favorite:

[min,x,max].sort()[1]
查看更多
放荡不羁爱自由
4楼-- · 2019-01-16 10:25

This does not want to be a "just-use-a-library" answer but just in case you're using Underscore/Lodash you can use .clamp:

_.clamp(yourInput, lowerBound, upperBound);

So that:

_.clamp(22, -10, 10); // => 10

Here is its implementation, taken from Lodash source:

/**
 * The base implementation of `_.clamp` which doesn't coerce arguments.
 *
 * @private
 * @param {number} number The number to clamp.
 * @param {number} [lower] The lower bound.
 * @param {number} upper The upper bound.
 * @returns {number} Returns the clamped number.
 */
function baseClamp(number, lower, upper) {
  if (number === number) {
    if (upper !== undefined) {
      number = number <= upper ? number : upper;
    }
    if (lower !== undefined) {
      number = number >= lower ? number : lower;
    }
  }
  return number;
}

Also, it's worth noting that Lodash makes single methods available as standalone modules, so in case you need only this method, you can just install it without the rest of the library:

npm i --save lodash.clamp
查看更多
登录 后发表回答