Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

clamp

Clamps a number within the inclusive range [min, max].

TypeScript
Copied!
1/**
2 * Clamps a number within the inclusive range [min, max].
3 *
4 * @param num - The number to clamp.
5 * @param min - The lower bound.
6 * @param max - The upper bound.
7 * @returns The clamped number.
8 */
9export function clamp(num: number, min: number, max: number): number {
10  return Math.min(Math.max(num, min), max);
11}
  • Simple and Efficient

    Utilizes Math.min and Math.max for optimal performance with minimal code.

  • Predictable Behavior

    Ensures a number always stays within the specified bounds, eliminating edge case errors.

  • Readability and Clarity

    Easy-to-read one-liner that conveys intent clearly without introducing complexity.

Tests | Examples

TypeScript
Copied!
1test('clamp - value within range', () => {
2  expect(clamp(5, 1, 10)).toBe(5);
3});
4
5test('clamp - value below min', () => {
6  expect(clamp(-5, 0, 10)).toBe(0);
7});
8
9test('clamp - value above max', () => {
10  expect(clamp(20, 0, 10)).toBe(10);
11});
12
13test('clamp - value at exact min', () => {
14  expect(clamp(0, 0, 5)).toBe(0);
15});
16
17test('clamp - value at exact max', () => {
18  expect(clamp(5, 0, 5)).toBe(5);
19});
20
21test('clamp - min and max are equal', () => {
22  expect(clamp(100, 5, 5)).toBe(5);
23});

Common Use Cases

  • UI Value Constraints

    Clamp slider inputs, scroll positions, or zoom levels within allowed ranges.

  • Animation and Physics

    Limit movement, velocity, or force values to avoid instability in visual or physical simulations.

  • Form Input Validation

    Restrict numeric form input values like age, quantity, or percentages to acceptable limits.

  • Data Normalization

    Constrain values to fixed domains before further processing or visualization.

  • Audio/Video Processing

    Keep audio volumes, brightness, or contrast settings within safe or recommended thresholds.

Codebase: Utilities -> Numbers -> clamp | Yevhen Klymentiev