将数字限制为细分市场的最优雅方式是什么? [英] What's the most elegant way to cap a number to a segment?

查看:161
本文介绍了将数字限制为细分市场的最优雅方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 x a b 是数字。我需要将 x 上限到段 [a,b] 的边界。

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

我可以写 Math.max(a,Math.min(x,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?

推荐答案

你这样做很标准。您可以定义一个实用程序 clamp 函数,如描述这里

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)

这篇关于将数字限制为细分市场的最优雅方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆