Packages@accelint/math
clamp
Clamps a number within the specified bounds
Usage
import { clamp } from '@accelint/math';
const result = clamp(5, 15, 10);
// 10
const belowMin = clamp(5, 15, 2);
// 5
const aboveMax = clamp(5, 15, 20);
// 15Reference
function clamp(min: number, max: number, value: number): numberParameters
| Parameter | Type | Description |
|---|---|---|
min | number | The lower bound to clamp to. |
max | number | The upper bound to clamp to. |
value | number | The number value to clamp to the given range. |
Returns
Returns the clamped value. If value is below min, returns min. If value is above max, returns max. Otherwise returns value.
Throws
RangeError- Throws ifmin > max.
Examples
Example: Clamping below minimum
import { clamp } from '@accelint/math';
const result = clamp(1, 2, 0);
// 1Example: Clamping above maximum
import { clamp } from '@accelint/math';
const result = clamp(1, 2, 3);
// 2Example: Value within range
import { clamp } from '@accelint/math';
const result = clamp(1, 3, 2);
// 2Good to know: The function validates that
mindoes not exceedmaxand throws aRangeErrorif this constraint is violated.
Related
- round - Rounds a number to specified precision