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.
Try it
Section titled “Try it”Import
Section titled “Import”import { clamp } from "1o1-utils";import { clamp } from "1o1-utils/clamp";Signature
Section titled “Signature”function clamp(params: { value: number; min: number; max: number }): numberParameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| value | number | Yes | The number to clamp |
| min | number | Yes | The lower bound (inclusive) |
| max | number | Yes | The upper bound (inclusive) |
Returns
Section titled “Returns”number — The clamped number within [min, max].
Examples
Section titled “Examples”clamp({ value: 15, min: 0, max: 10 }); // 10clamp({ value: -5, min: 0, max: 10 }); // 0clamp({ value: 5, min: 0, max: 10 }); // 5// Bounds are swapped automatically when min > maxclamp({ value: 5, min: 10, max: 0 }); // 5// Floating-point valuesclamp({ value: 1.5, min: 1, max: 2 }); // 1.5clamp({ value: 2.5, min: 1, max: 2 }); // 2Edge Cases
Section titled “Edge Cases”- Throws if any of
value,min, ormaxis not a number or isNaN. - A zero-width range (
min === max) always returns that bound. - Works with
Infinitybounds — e.g.{ value: 1e10, min: 0, max: Infinity }returns1e10. - When
min > max, the bounds are swapped silently.
Also known as
Section titled “Also known as”restrict, bound, constrain, limit, range cap
Prompt suggestion
Section titled “Prompt suggestion”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.