@valeera/mathx
Version:
A math library written in TS.
16 lines (15 loc) • 558 B
text/typescript
/**
* @function clamp
* @desc 将目标值限定在指定区间内。假定min小于等于max才能得到正确的结果。
* @see clampSafe
* @param {number} val 目标值
* @param {number} min 最小值,必须小于等于max
* @param {number} max 最大值,必须大于等于min
* @returns {number} 限制之后的值
* @example Mathx.clamp(1, 0, 2); // 1;
* Mathx.clamp(-1, 0, 2); // 0;
* Mathx.clamp(3, 0, 2); // 2;
*/
export const clamp = (val: number, min: number, max: number): number => {
return Math.max(min, Math.min(max, val));
};