Standard Toolkit
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);
// 15

Reference

function clamp(min: number, max: number, value: number): number

Parameters

ParameterTypeDescription
minnumberThe lower bound to clamp to.
maxnumberThe upper bound to clamp to.
valuenumberThe 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 if min > max.

Examples

Example: Clamping below minimum

import { clamp } from '@accelint/math';

const result = clamp(1, 2, 0);
// 1

Example: Clamping above maximum

import { clamp } from '@accelint/math';

const result = clamp(1, 2, 3);
// 2

Example: Value within range

import { clamp } from '@accelint/math';

const result = clamp(1, 3, 2);
// 2

Good to know: The function validates that min does not exceed max and throws a RangeError if this constraint is violated.

  • round - Rounds a number to specified precision

On this page