Sam*_*lle 109 javascript coding-style
比方说x
,a
和b
是数字.我需要x
限制段的范围[a, b]
.
我可以写Math.max(a, Math.min(x, b))
,但我不认为这很容易阅读.有没有人有一种聪明的方式以更易读的方式写这个?
Ott*_*ger 178
你这样做是非常标准的.您可以定义一个工具clamp
像描述的功能在这里:
/**
* 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);
};
Run Code Online (Sandbox Code Playgroud)
(虽然扩展语言内置函数通常不受欢迎)
dwe*_*ves 53
一个较少"数学"导向的方法,但也应该工作,这样,</>测试暴露(可能比minimaxing更容易理解)但它实际上取决于你的"可读"是什么意思
function clamp(num, min, max) {
return num <= min ? min : num >= max ? max : num;
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*dym 36
ECMAScript 2017的更新:
Math.clamp(x, lower, upper)
Run Code Online (Sandbox Code Playgroud)
但请注意,截至今天,这是第1阶段提案.在获得广泛支持之前,您可以使用polyfill.
CAF*_*FxX 12
Math.clip = function(number, min, max) {
return Math.max(min, Math.min(number, max));
}
Run Code Online (Sandbox Code Playgroud)
如果您能够使用 es6 箭头函数,您还可以使用部分应用程序方法:
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
Run Code Online (Sandbox Code Playgroud)
这不是一个"只是使用一个库"的答案,但为了防止您使用Underscore/Lodash,您可以使用.clamp
:
_.clamp(yourInput, lowerBound, upperBound);
Run Code Online (Sandbox Code Playgroud)
以便:
_.clamp(22, -10, 10); // => 10
Run Code Online (Sandbox Code Playgroud)
这是它的实现,取自Lodash 来源:
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
此外,值得注意的是Lodash将单个方法作为独立模块提供,因此如果您只需要此方法,则可以在没有其余库的情况下安装它:
npm i --save lodash.clamp
Run Code Online (Sandbox Code Playgroud)
这将三元选项扩展为 if/else,缩小后相当于三元选项,但不牺牲可读性。
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
}
Run Code Online (Sandbox Code Playgroud)
缩小到 35b(如果使用 则缩小到 43b function
):
const clamp=(c,a,l)=>c<a?a:c>l?l:c;
Run Code Online (Sandbox Code Playgroud)
此外,根据您使用的性能工具或浏览器,您会得到基于数学的实现或基于三元的实现是否更快的各种结果。在性能大致相同的情况下,我会选择可读性。
归档时间: |
|
查看次数: |
89212 次 |
最近记录: |