Skip to content

Scale

Scaling takes an input value within some range and scales (or maps) it to a target range, most likely a scalar.

For example, say you have a value of 105, that lies on a scale of 0..1024, common for analog sensors. What is the proportional value of 105? We want to scale from an input range of 0…1024 to the scalar range of 0..1.

A basic Numbers.scale function (included in ixfx) looks like this:

const scale = (v, inMin, inMax, outMin, outMax) => {
return (v - inMin) / (inMax - inMin) * (outMax - outMin) + outMin;
};
scale(105, 0, 1024, 0, 1); // 0.102

This is how it looks in action. The default output range is 0..1, so we don’t need to include it.

import { scale } from 'https://unpkg.com/ixfx/dist/numbers.js'
// Scales 10 on the range of 0-100,
// with an output range of 0-1.
scale(10, 0, 100); // 0.1
// Scales 20 on a range of 20-40
scale(20, 20, 40); // 0

You can also specify an output range. Below, we scale 30 from an input range of 20-40 (ie it’s 50% of that scale) to an output range of 100-200, yielding a value of 150.

scale(30, 20, 40, 100, 200); // 150

If the input value is outside of the specified input range, the output value will likewise be outside of the output range. Clamp the value to ensure the output range is respected, or use Numbers.scaledClamped .

import { scale, clamp, scaleClamped } from 'https://unpkg.com/ixfx/dist/numbers.js'
// 11 is beyond input range of 0-10, so we get
// an output beyond expected range of 0..1:
scale(11, 0, 10); // 1.1
// Clamp solves that:
clamp(scale(11, 0, 10)); // 1
// Alternatively, use scaleClamped:
scaleClamped(11, 0, 10); // 1

Scaler

If you’re scaling things by the same value repeatedly, rather than put the scale ranges all over your code, use Numbers.scaler to create a reusable scaling function.

import { scaler } from 'https://unpkg.com/ixfx/dist/numbers.js'
// Scale things with an input range of 10..100. The output range defaults to 0..1
const s = scaler(10,100);
s(20); // 0.11