Lib
Number Utilities — clamp
Clamp a number within a range using a tiny, zero‑dependency helper function.
clamp
clamp constrains a number to lie within a given inclusive range. If the value is lower than the minimum, you get the minimum; if it’s higher than the maximum, you get the maximum; otherwise you get the original value.
This helper is small, predictable, and safe to use in performance‑sensitive paths.
API
function clamp(value: number, [min, max]: [number, number]): number;Prop
Type
Usage
import { clamp } from '@loke/ui/number';
// Basic clamping
clamp(15, [0, 10]); // 10
clamp(-5, [0, 10]); // 0
clamp(7, [0, 10]); // 7
// Often useful for UI values:
const opacity = clamp(userInputOpacity, [0, 1]); // keep it between 0 and 1
const progress = clamp(downloadPct, [0, 100]); // constrain percentage for a progress barCommon patterns
Normalize untrusted input
function coerceRating(input: number) {
// Ratings allowed from 1 to 5
return clamp(Math.round(input), [1, 5]);
}Bound UI positions/sizes
function constrainX(x: number, containerWidth: number) {
return clamp(x, [0, containerWidth]);
}Keep easing values in range
// Ensure t is within [0,1] before applying an easing function
const t = clamp(rawT, [0, 1]);
const eased = t * t * (3 - 2 * t);Edge cases
- If
valueequals the bounds, the bound is returned (inclusive). - If
min === max,clamp(value, [min, min])always returnsmin. - Assumes
min <= max(if unsure, normalize first).
// Normalize a range defensively
function clampSafe(value: number, a: number, b: number) {
const min = Math.min(a, b);
const max = Math.max(a, b);
return clamp(value, [min, max]);
}Performance
clamp uses only Math.max/Math.min and is effectively constant‑time. It’s safe to call in render loops, animations, or pointer‑move handlers.
// Internals (for reference)
function clamp(value: number, [min, max]: [number, number]): number {
return Math.min(max, Math.max(min, value));
}When to use
- Bounding percentages, progress, opacity, zoom levels
- Constraining drag positions to a viewport or container
- Sanitizing user input into valid ranges
- Keeping animation parameters in stable bounds
// Example: Keep zoom between 0.5x and 3x
const zoom = clamp(requestedZoom, [0.5, 3]);