什么是最优雅的方式来覆盖一个数字段? [英] Whats the most elegant way to cap a number to a segment?

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

问题描述

让我们说 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 readeable 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天全站免登陆