The lodash method _.clamp exported as a module, clamps numbers within inclusive lower and upper bounds.
npx @tessl/cli install tessl/npm-lodash--clamp@4.0.0The lodash method _.clamp exported as a Node.js module. Clamps numbers within inclusive lower and upper bounds to constrain values within a specified range.
npm install lodash.clampconst clamp = require('lodash.clamp');For ES modules:
import clamp from 'lodash.clamp';const clamp = require('lodash.clamp');
// Clamp with lower and upper bounds
clamp(-10, -5, 5);
// => -5
clamp(10, -5, 5);
// => 5
clamp(3, -5, 5);
// => 3
// Clamp with only upper bound (lower bound becomes undefined)
clamp(10, 5);
// => 5
clamp(3, 5);
// => 3Constrains a number within inclusive lower and upper bounds.
/**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @param {*} number The number to clamp (will be converted to number)
* @param {number} [lower] The lower bound (optional)
* @param {number} upper The upper bound
* @returns {number} Returns the clamped number
*/
function clamp(number, lower, upper);Parameter Details:
number (any): The value to clamp. Will be converted to a number using internal type conversion:
valueOf() method if available, then string conversionlower (number, optional): The lower bound. If upper is undefined, this becomes the upper bound and lower becomes undefinedupper (number): The upper bound. Required parameterReturn Value:
Type Conversion Behavior:
The function performs comprehensive type conversion on all parameters:
// String conversion examples
clamp("10", "2", "8"); // => 8
clamp("3.5", "1", "5"); // => 3.5
clamp("0b1010", "0", "15"); // => 10 (binary)
clamp("0o17", "0", "20"); // => 15 (octal)
// Object conversion examples
clamp({valueOf: () => 7}, 0, 5); // => 5
clamp([3], 0, 10); // => 3
// Invalid input handling
clamp(Symbol(), 0, 10); // => NaN
clamp("invalid", 0, 10); // => NaN
clamp(null, 0, 10); // => 0
clamp(undefined, 0, 10); // => NaNFlexible Parameter Patterns:
// Three parameters: number, lower, upper
clamp(15, 5, 10); // => 10
// Two parameters: number, upper (lower becomes undefined)
clamp(15, 10); // => 10
clamp(5, 10); // => 5
// Edge cases with undefined bounds
clamp(5, undefined, 10); // => 5
clamp(5, 2, undefined); // => 5 (no upper constraint)Common Use Cases:
Examples:
const clamp = require('lodash.clamp');
// User input validation
function setVolume(level) {
return clamp(level, 0, 100); // Ensure volume is 0-100
}
// Percentage calculations
function calculatePercent(value, total) {
const percent = (value / total) * 100;
return clamp(percent, 0, 100); // Cap at 100%
}
// Animation frame clamping
function updateProgress(current, duration) {
const progress = current / duration;
return clamp(progress, 0, 1); // Keep between 0 and 1
}