Skip to content

Wrap

Let’s say we are using angle for colour hue. It has a range of 0..360. If we’re cycling through the hue, at some point we need to go from the upper range of hue back to the start point.

For example, if hue is 0 and we want to go ‘back’ by 10 degrees, the result should be 350, not -10. Or if we’re at 300 degrees and want to add 70 degrees, the value should be 10 degrees, not 370. We want the value to always be within the ‘safe’ range.

Numbers.wrapInteger does this arithmetic for you.

import { wrapInteger } from 'https://unpkg.com/ixfx/dist/numbers.js';
wrapInteger(200); // 200 - fine, within range
wrapInteger(400); // 40 - wraps past 360 to 40
wrapInteger(-90); // 270

A custom range can be provided for wrapping: wrapInteger(value:number, min:number, max:number):number. The minimum is inclusive, the maximum is exclusive.

import { wrapInteger } from 'https://unpkg.com/ixfx/dist/numbers.js';
wrapInteger(5, 20, 30); // 25
// Max value is exlusive, so it wraps to min:
wrapInteger(30, 20, 30); // 20

Numbers.wrap is the same, but doesn’t enforce any integer limitations.

import { wrap } from 'https://unpkg.com/ixfx/dist/numbers.js';
wrap(10.5,0,10); // 0.5;
wrap(-0.5,0,10); // 9.5