Skip to content

clamp function ​

Restricts a number to an interval.

ts
import { clamp } from 'utils';

Signature ​

ts
export function clamp(value: number, min = 0, max = 1): number

Parameters ​

NameDescription
valueThe number to restrict.
minThe lower bound. Defaults to 0.
maxThe upper bound. Defaults to 1.

Returns ​

value within the bounds, or the nearest bound.

Example ​

ts
clamp(15, 0, 10); // 10
clamp(1.5); // 1

Tests ​

Line coverage: 100 %.

  • ✅ clamps 5 into [0, 10] as 5
  • ✅ clamps -5 into [0, 10] as 0
  • ✅ clamps 15 into [0, 10] as 10
  • ✅ clamps -5 into [10, 0] as 0
  • ✅ takes the defaults

Source ​

src/math/clamp.ts (on GitHub)

Used by ​

  • remap: Maps a value from an input range to an output range, such as a sensor reading to a gauge angle.
  • createSvgBarRangePath: Creates the d of the part of a bar between two ratios, across its whole thickness, in any group: the fill level of a bar graph (0 to the value) or a threshold zone.
Source code
ts
/**
 * Restricts a number to an interval.
 *
 * @param value - The number to restrict.
 * @param min - The lower bound. Defaults to `0`.
 * @param max - The upper bound. Defaults to `1`.
 * @returns `value` within the bounds, or the nearest bound.
 * @example
 * clamp(15, 0, 10); // 10
 * clamp(1.5); // 1
 */
export function clamp(value: number, min = 0, max = 1): number {
  return Math.min(Math.max(value, min), max);
}
Test file
ts
import { clamp } from './clamp';

describe(clamp, () => {
  it.for([
    [5, 0, 10, 5],
    [-5, 0, 10, 0],
    [15, 0, 10, 10],
    [-5, 10, 0, 0],
  ] as const)('clamps %s into [%s, %s] as %s', ([value, min, max, expected]) => {
    expect(clamp(value, min, max)).toBe(expected);
  });

  it('takes the defaults', () => {
    expect(clamp(1.5)).toStrictEqual(clamp(1.5, 0, 1));
  });
});

Keywords: clamp, math, function

Generated from the JSDoc of the sources.