Skip to content

Clamp

Clamping guarantees the return value is within the provided range.

Why?

For example, maybe you’re computing a relative value based on some sensor input. By activating the sensor, it seems the maximum is about 500. We want a percentage scale from 0..1:

const v = sensorValue / 500;

But what if sensorValue rises above 500? Our neat percentage value of v will be greater than 1 (ie. more than 100%). Other parts of our code might purposefully be able to handle this, but there are times where exceeding 100% cannot be permitted. Likewise, we might not want v to be less than 0% because of assumptions made in other parts of our code.

To do this manually, we might write:

let v = sensorValue / 500;
if (v > 1) v = 1;
else if (v < 0) v = 0;
// Now v is guaranteed to be between 0..1, inclusive

Usage

The above example is really all that Numbers.clamp is doing.

It takes an input value and optionally a range to clamp within. By default it uses a minimum of 0, a maximum of 1:

import { Numbers } from 'https://unpkg.com/@ixfx/bundle';
Numbers.clamp(0.5); // 0.5
Numbers.clamp(2); // 1.0
Numbers.clamp(-0.2); // 0.0

Revisiting an earlier example, we can scale a sensor value which we expect to be on the range of 0..500 and clamp it to be sure we’re always within 0..1:

import { Numbers } from 'https://unpkg.com/@ixfx/bundle';
// Create our resuable scaling function
const sensorScale = Numbers.scaler(0, 500);
Numbers.clamp(sensorScale(250)); // 0.5
Numbers.clamp(sensorScale(500)); // 1.0
Numbers.clamp(sensorScale(505)); // 1.0 - although out of expected range
Numbers.clamp(sensorScale(-1)); // 0.0 - although out of expected range

A custom output range can be used as well:

// clamp(value:number, min:number, max:number):number
Numbers.clamp(30, 50, 100); // 50

If you are working with bipolar values (-1..1), use the Module Numbers.Bipolar .

import { Numbers } from 'https://unpkg.com/@ixfx/bundle';
Numbers.Bipolar.clamp(1.1); // 1
Numbers.Bipolar.clamp(0.9); // 0.9
Numbers.Bipolar.clamp(-1.1); // -1