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, lets say you have an analog sensor that yields values between 100…832. If you get a reading of 110, you probably care less that it’s 110, but rather what its relative value is, with respect to the range of 100..832. It would be much easier in your code if you just work with these relative scalar values.

What we want to do then is scale or map the range of 100..832 to 0..1

A basic implementation of a scaling function is below, essentially the same one in ixfx:

const scale = (v, inMin, inMax, outMin, outMax) => {
return (v - inMin) / (inMax - inMin) * (outMax - outMin) + outMin;
};
scale(110, 100, 832, 0, 1); // 0.013

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

import { Numbers } from 'https://unpkg.com/@ixfx/bundle'
// Scales 110 on the range of 100-832,
// with an output range of 0-1.
Numbers.scale(110, 100, 832); // 0.013
// Scales 20 on a range of 20-40
Numbers.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.scaleClamped .

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

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 { Numbers } from 'https://unpkg.com/@ixfx/bundle'
// Scale things with an input range of 10..100. The output range defaults to 0..1
const s = Numbers.scaler(10,100);
s(20); // 0.11