For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/bigint/clamp.md.

clamp (for BigInts) es-toolkit

Restricts a BigInt to a given range.

const clamped = clamp(value, maximum);
const clamped = clamp(value, minimum, maximum);
Info

This function is available exclusively from es-toolkit/bigint to avoid potential conflicts with similar functions for other numeric types.

Usage

clamp(value, maximum)

Use clamp with two arguments when you only want an upper limit. Anything above the maximum comes back as the maximum, and anything else is returned unchanged.

import { clamp } from 'es-toolkit/bigint';

console.log(clamp(10n, 5n)); // 5n, because 10n is above the maximum
console.log(clamp(3n, 5n)); // 3n, already within the limit

Parameters

valuebigintrequired

The BigInt to clamp.

maximumbigintrequired

The upper bound, inclusive.

Returns

Returns the BigInt, capped at the maximum.

bigint

clamp(value, minimum, maximum)

Use clamp with three arguments when you want both a lower and an upper limit. Math.min and Math.max cannot accept BigInts, so this is the way to do it.

import { clamp } from 'es-toolkit/bigint';

console.log(clamp(10n, 0n, 5n)); // 5n, above the maximum
console.log(clamp(-10n, 0n, 5n)); // 0n, below the minimum
console.log(clamp(3n, 0n, 5n)); // 3n, already within the range

// Both bounds are inclusive
console.log(clamp(0n, 0n, 5n)); // 0n
console.log(clamp(5n, 0n, 5n)); // 5n

// Negative ranges work too
console.log(clamp(-10n, -5n, -1n)); // -5n

Because BigInts are compared exactly, bounds far past Number.MAX_SAFE_INTEGER still behave the way you would expect.

import { clamp } from 'es-toolkit/bigint';

const maxUint64 = 18446744073709551615n;
console.log(clamp(20000000000000000000n, 0n, maxUint64)); // 18446744073709551615n

Parameters

valuebigintrequired

The BigInt to clamp.

minimumbigintrequired

The lower bound, inclusive.

maximumbigintrequired

The upper bound, inclusive.

Returns

Returns the BigInt, constrained to the range.

bigint
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.