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:08

If you don’t want to define any function, writing it like Math.min(Math.max(x, a), b) isn’t that bad.

查看更多
Rolldiameter
3楼-- · 2019-01-16 10:10

Update for ECMAScript 2017:

Math.clamp(x, lower, upper)

But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.

查看更多
看我几分像从前
4楼-- · 2019-01-16 10:10

In the spirit of arrow sexiness, you could create a micro clamp/constrain/gate/&c. function using rest parameters

var clamp = (...v) => v.sort((a,b) => a-b)[1];

Then just pass in three values

clamp(100,-3,someVar);

That is, again, if by sexy, you mean 'short'

查看更多
▲ chillily
5楼-- · 2019-01-16 10:13

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

/**
 * 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)

查看更多
神经病院院长
6楼-- · 2019-01-16 10:14

If you are able to use es6 arrow functions, you could also use a partial application approach:

const clamp = (min, max) => (value) =>
    value < min ? min : value > max ? max : value;

clamp(2, 9)(8); // 8
clamp(2, 9)(1); // 2
clamp(2, 9)(10); // 9

or

const clamp2to9 = clamp(2, 9);
clamp2to9(8); // 8
clamp2to9(1); // 2
clamp2to9(10); // 9
查看更多
贼婆χ
7楼-- · 2019-01-16 10:17
Math.clip = function(number, min, max) {
  return Math.max(min, Math.min(number, max));
}
查看更多
登录 后发表回答