Skip to content

Range Clamp

Clamp a calculation result to a specified range.

Syntax

expression | [min, max]

Basic Usage

javascript
import { calc } from "a-calc";

calc("150 | [0, 100]"); // '100' (clamped to max)
calc("-50 | [0, 100]"); // '0'   (clamped to min)
calc("50 | [0, 100]"); // '50'  (within range)

With Expressions

javascript
calc("50 + 80 | [0, 100]"); // '100'
calc("(a + b) * c | [0, 100]", { a: 10, b: 20, c: 5 }); // '100'

Variable Boundaries

Use @ prefix to reference variables as boundaries:

javascript
calc("150 | [@min, @max]", { min: 0, max: 100 }); // '100'

calc("value | [@config.limits.min, @config.limits.max]", {
  value: 50,
  config: { limits: { min: 0, max: 100 } },
}); // '50'

Combining with Formatting

javascript
calc("150.567 | [0, 100] =2"); // '100.00'
calc("15000 | [0, 10000] ,"); // '10,000'
calc("1.5 | [0, 1] %"); // '100%'
calc("150 | [0, 100] +"); // '+100'

Real-World Examples

Progress Bar

javascript
function getProgress(current, total) {
  return calc("current / total * 100 | [0, 100]", { current, total });
}

getProgress(150, 100); // '100'
getProgress(-10, 100); // '0'

Volume Control

javascript
function setVolume(delta, current) {
  return calc("current + delta | [0, 100]", { current, delta });
}

setVolume(30, 90); // '100'
setVolume(-50, 30); // '0'

Price Protection

javascript
calc("price | [@floor, @ceiling]", {
  price: 1500,
  floor: 100,
  ceiling: 1000,
}); // '1000'

Equivalent Conditional Expression

javascript
// Range clamp
calc("x | [0, 100]", { x: 150 });

// Equivalent conditional
calc("x < 0 ? 0 : (x > 100 ? 100 : x)", { x: 150 });

Released under the MIT License