es-toolkit
Version:
A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.
37 lines (36 loc) • 1.46 kB
JavaScript
import { toNumber } from "../util/toNumber.mjs";
//#region src/compat/math/clamp.ts
/**
* Clamps a number within the specified bounds.
*
* This function takes a number and one or two bounds, and returns the number clamped within the specified bounds.
* If only one bound is provided, it returns the minimum of the value and the bound.
*
* @param value - The number to clamp.
* @param bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided.
* @param [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit.
* @returns The clamped number within the specified bounds.
*
* @example
* const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5
* const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15
* const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5
* const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15
*/
function clamp(value, bound1, bound2) {
if (bound2 === void 0) {
bound2 = bound1;
bound1 = void 0;
}
if (bound2 !== void 0) {
bound2 = toNumber(bound2);
value = Math.min(value, Number.isNaN(bound2) ? 0 : bound2);
}
if (bound1 !== void 0) {
bound1 = toNumber(bound1);
value = Math.max(value, Number.isNaN(bound1) ? 0 : bound1);
}
return value;
}
//#endregion
export { clamp };