Skip to content

clamp

Clamps a number to a given range. Returns min if value is below the range, max if above, otherwise value. If min is greater than max, the bounds are swapped automatically.

import { clamp } from "1o1-utils";
import { clamp } from "1o1-utils/clamp";
function clamp(params: { value: number; min: number; max: number }): number
NameTypeRequiredDescription
valuenumberYesThe number to clamp
minnumberYesThe lower bound (inclusive)
maxnumberYesThe upper bound (inclusive)

number — The clamped number within [min, max].

clamp({ value: 15, min: 0, max: 10 }); // 10
clamp({ value: -5, min: 0, max: 10 }); // 0
clamp({ value: 5, min: 0, max: 10 }); // 5
// Bounds are swapped automatically when min > max
clamp({ value: 5, min: 10, max: 0 }); // 5
// Floating-point values
clamp({ value: 1.5, min: 1, max: 2 }); // 1.5
clamp({ value: 2.5, min: 1, max: 2 }); // 2
  • Throws if any of value, min, or max is not a number or is NaN.
  • A zero-width range (min === max) always returns that bound.
  • Works with Infinity bounds — e.g. { value: 1e10, min: 0, max: Infinity } returns 1e10.
  • When min > max, the bounds are swapped silently.

restrict, bound, constrain, limit, range cap

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use clamp to restrict a slider value between min and max.