Skip to content

Scalar

Data coming in from events, sensors etc. can have radically different scales or units. Rather than having to juggle these differences throughout your code, a strategy is to try to normalise it as soon as you can, getting it on a relative percentage scale of 0..1 (meaning: 0% .. 100%).

We call this a scalar.

Scalars can be compared more readily. 0.5 (ie. 50%) can represent half volume level, or half of the screen width. That’s easier to manage than having to work with the equivalent absolute values of -12dB and 800, and much less of your code has to change if different scaling is needed later on.

It’s easy to apply modulation factors and eventually to map the relative value to some absolute value in the output domain. In the below example, we can easily apply the same scalar to different things:

// Scalar value
const v = 0.5;
// Get x coordinate at 50%
const x = v * window.innerWidth;
// Get a hue at 50%
const hue = v * 360;

In general, try to keep your values as scalars for as long as possible before making them absolute.

Making absolute

If the input range is a percentage, Data.scalePercentages adapts to a new output percentage range. While scale can be used for this, scalePercentage will throw errors if values are outside of legit percentage ranges, helping you to catch errors.

// repl-pad
import { scalePercentages } from 'https://unpkg.com/ixfx/dist/numbers.js'
// Scale 0.5 to be on a 0.0->0.10 range
scalePercentages(0.5, 0, 0.10) // 0.05 (5%)

Very similarly named is Data.scalePercent . It also works with an input percentage range, but it has no restrictions on output range.

// repl-pad
import { scalePercent } from 'https://unpkg.com/ixfx/dist/numbers.js'
// Scales 50% to the range of 10->20
scalePercent(0.5, 10, 20); // 15