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, assuming that 500 is the maximum. We want a percentage scale from 0..1:
const v = sensorValue / 500;
But if sensorValue
rises above 500 unexpectedly, 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 { clamp } from 'https://unpkg.com/ixfx/dist/numbers.js';clamp(0.5); // 0.5clamp(2); // 1.0clamp(-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 { clamp, scaler } from 'https://unpkg.com/ixfx/dist/numbers.js';
// Create our resuable scaling functionconst sensorScale = scaler(0, 500);
clamp(sensorScale(250)); // 0.5clamp(sensorScale(500)); // 1.0clamp(sensorScale(505)); // 1.0 - although out of expected rangeclamp(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):numberclamp(30, 50, 100); // 50
If you are working with bipolar values (-1..1), use the Module Numbers.Bipolar .
import { Bipolar } from 'https://unpkg.com/ixfx/dist/numbers.js';Bipolar.clamp(1.1); // 1Bipolar.clamp(0.9); // 0.9Bipolar.clamp(-1.1); // -1