src/clamp.js
zzmq.dev@gmail.com/mathkit / src / clamp.js
@ 9271926f
Download
Ladder Summary
- file Exports a `clamp` function that validates all arguments are finite numbers, swaps the lower and upper bounds if they are provided in reverse order, and returns the input number constrained to the inclusive range or `undefined` when validation fails.
/**
* Clamps a number `n` to be within the inclusive range defined by `lo` and `hi`.
*
* @param {number} n - The number to clamp.
* @param {number} lo - The lower bound of the range.
* @param {number} hi - The upper bound of the range.
* @returns {number|undefined} The clamped value, or `undefined` if any argument is not a finite number.
*/
export function clamp(n, lo, hi) {
// Validate inputs – all must be finite numbers
if (
typeof n !== "number" ||
typeof lo !== "number" ||
typeof hi !== "number" ||
!Number.isFinite(n) ||
!Number.isFinite(lo) ||
!Number.isFinite(hi)
) {
return undefined;
}
// Ensure lower bound is not greater than upper bound; if it is, swap them
if (lo > hi) {
const tmp = lo;
lo = hi;
hi = tmp;
}
if (n < lo) return lo;
if (n > hi) return hi;
return n;
}