Skip to content
VersionSize

clamp

The clamp utility restricts a numeric value to be within a specified range. If the value is smaller than the minimum, it returns the minimum. If it's larger than the maximum, it returns the maximum. Otherwise, it returns the value itself.

Implementation

View Source Code
ts
/**
 * The `clamp` function restricts a number to be within a specified range.
 *
 * @example
 * ```ts
 * clamp(5, 1, 10) // 5
 * clamp(0, 1, 10) // 1
 * clamp(15, 1, 10) // 10
 * ```
 *
 * @param n - The number to be clamped.
 * @param min - The minimum value of the range.
 * @param max - The maximum value of the range.
 *
 * @returns The clamped number.
 */
export function clamp(n: number, min: number, max: number): number {
  return Math.min(Math.max(n, min), max);
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Robust: Gracefully handles cases where min is greater than max by swapping them.
  • Type-safe: Properly typed for numeric inputs and results.

API

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

Parameters

  • value: The numeric value to restrict.
  • min: The lower bound of the range.
  • max: The upper bound of the range.

Returns

  • The restricted value within the [min, max] range.

Examples

Basic Clamping

ts
import { clamp } from '@vielzeug/toolkit';

// Within range
clamp(5, 0, 10); // 5

// Below range
clamp(-5, 0, 10); // 0

// Above range
clamp(15, 0, 10); // 10

Real-world Usage (UI Progress)

ts
import { clamp } from '@vielzeug/toolkit';

function setProgress(percent: number) {
  // Ensure percent is always between 0 and 100
  const safePercent = clamp(percent, 0, 100);
  console.log(`Progress: ${safePercent}%`);
}

Implementation Notes

  • Performance-optimized using Math.min and Math.max.
  • If min > max, the utility automatically swaps them to ensure consistent behavior.
  • Throws TypeError if any of the arguments are not numbers.

See Also

  • min: Find the minimum value in a set.
  • max: Find the maximum value in a set.
  • isWithin: Check if a number is within a range without changing it.