Bipolar
The scalar range of 0..1 works for most cases, but sometimes the bipolar scale of -1..1 makes more sense. In this range, 0 represents neutral. It’s still a percentage scaling, but now -100% to 100%, instead of than 0 to 100%.
An example use case is panning of audio in the stereo field:
pan = -1; // Far leftpan = 0; // Centerpan = 1; // Far right
Bipolar values are used by jitter to have values go above and below a given value.
As with scalars, there are few things we’d like to be able to do with them - especially to help us avoid being out-of-range. The basics are:
Bipolar.clamp(value); // Clamp to -1..1 rangeBipolar.fromScalar(value); // Scale a 0..1 value to -1..1 range
Nudging
A common need is to nudge a bipolar value toward its neutral value of zero. Sort of like bringing something into balance. We don’t care if it’s above or below zero, we just want to draw it to zero. towardZero helps.
import { Bipolar } from 'https://unpkg.com/ixfx/dist/numbers.js';
// Syntax: towardZero(bipolarValue, amountToNudgeBy);
// Nudge -1 toward zero by 0.1Bipolar.towardZero(-1, 0.1); // -0.9
// Nudge 1 toward zero by 0.1Bipolar.towardZero( 1, 0.1); // 0.9
Immutable
If you’re working with bipolar values a lot, there’s also immutable . It returns an immutable wrapper around a value, hanging the same functions off it and making sure it’s always within bipolar range.
import { Bipolar } from 'https://unpkg.com/ixfx/dist/numbers.js';
// If you don't provide an initial value, 0% is usedlet b = Bipolar.immutable(); // { value: 0 }
// Add 0.1 to the bipolar valueb = b.add(0.1);
// Get the value as a numberb.value; // 0.1
import { Bipolar } from 'https://unpkg.com/ixfx/dist/numbers.js';
let b = Bipolar.immutable(1);b = b.add(-0.5); // { value: 0.5 }b = b.multiply(0.1); // { value: 0.05 }b = b.inverse(); // { value: -0.05 }b = b.towardZero(0.01); // { value: -0.04 }
// Interpolate to a value of 1 by 0.1b = b.interpolate(0.1, 1);
The wrapper converts to a number when needed:
import { Bipolar } from 'https://unpkg.com/ixfx/dist/data.js';let b = Bipolar.immutable(1); // { value: 1 }const x = b + 10; // x = 11
Output scaling
toScalar scales a bipolar value to 0..1 range.
import { Bipolar } from 'https://unpkg.com/ixfx/dist/data.js';Bipolar.toScalar(-1); // -100% becomes 0% (0)Bipolar.toScalar(0); // 0% becomes 50% (0.5)Bipolar.toScalar(1); // 100% becomes 100% (1)