Advanced
interpolate has a few different ways of being used.
The basic approach is where you provide the amount, A and B values and options:
const value = interpolate(amount, a, b, options);// Get back interpolated result as a number
There are a few alternatives if you’re calling interpolate in a few places in your code. interpolate
returns a function which you can store and pass around in your code.
If you have a fixed interpolation amount, but you want to vary A and B:
// Provide an interpolation amount and optional optionsconst i = interpolate(amount, options)
// Get back a function which takes A & B valuesi(from, to); // Yields interpolated numeric value
You’re re-using A and B values, but varying amount:
// Provide A & B values, and optionsconst i = interpolate(a, b, options);
// Get back a function which takes interpolation amountconst i(amount); // Yields interpolated numeric value
The options for the interpolate function can be left out. It has a single property, limits
which determines how to behave if interpolation amount exceeds 0..1.
- ‘clamp’: clamp returned value to within A & B (inclusive). This is the default.
- ‘wrap’: value wraps from end to start
- ‘ignore’: allow return values which exceed A & B.
For example:
import { interpolate } from 'https://unpkg.com/@ixfx/numbers/bundle';interpolate(1.1, 100, 200, { limits: `clamp` }); // 200interpolate(1.1, 100, 200, { limits: `wrap` }); // 110interpolate(1.1, 100, 200, { limits: `ignore` }); // 210
Interpolators
The interpolators Modulation.interpolatorInterval and Modulation.interpolatorStepped use the same options as Numbers.interpolate .
This allows us to use an easing curve for non-linear interpolation, determine what to do if interpolation range is breached and provide a custom transform function. For more: Type Modulation.InterpolateOptions
// Use quadIn easing, wrapping the interpolation amountinterpolatorInterval({ mins: 1 }, 10, 100, { easing: `quadIn`, limits: `wrap`});
Re-targeting
The interpolators both return a function to compute the interpolated value. We can use this to re-target the interpolation, allowing A and/or B points to be adjusted from their initial values.
Note:
- Order of parameters is ‘B, A’; the opposite when creating. This is because it’s more common to want to only adjust the target value.
- The change internally mutates the interpolator. Subsequent calls to the function make use of the changed A & B values.
const compute = interpolatorInterval({ mins: 1 }, 100, 200);
// A single parameter sets the B valuecompute(250); // Use a new range of 100->250 and return computed valuecompute(); // Compute value using 100->250 range
// Two parameters set B, Acompute(300, 150); // Use a new range of 150->300 and return computed value