Skip to content

Math

js
import { 
clamp
,
lerp
,
map
} from '@studiometa/js-toolkit/utils';

Values in, values out. For anything with a time dimension — damping, springs, inertia — see Motion.

Ranges

js
import { 
clamp
,
clamp01
} from '@studiometa/js-toolkit/utils';
clamp
(15, 0, 10); // 10
clamp
(-5, 0, 10); // 0
clamp01
(1.5); // 1

clamp

ts
clamp(value: number, min: number, max: number): number

Keep a value inside a range.

clamp01

ts
clamp01(value: number): number

Keep a value inside 0 → 1. It is the case that comes up in every progress calculation, so it has its own name and no arguments to get the wrong way round.

Interpolation

js
import { 
lerp
,
map
} from '@studiometa/js-toolkit/utils';
lerp
(0, 100, 0.5); // 50
map
(5, 0, 10, 0, 100); // 50

lerp

ts
lerp(min: number, max: number, ratio: number): number

Interpolate between two values by a 0 → 1 ratio.

map

ts
map(value: number, inputMin: number, inputMax: number, outputMin: number, outputMax: number): number

Re-scale one range onto another. It is lerp with the input range worked out for you.

Wrapping and folding

js
import { 
fold
,
wrap
} from '@studiometa/js-toolkit/utils';
wrap
(11, 0, 10); // 1 — it comes back round
fold
(11, 0, 10); // 9 — it bounces back

Two behaviours, two names, no flag.

wrap

ts
wrap(value: number, min: number, max: number): number

A carousel that loops: past the end, it comes back round to the start.

fold

ts
fold(value: number, min: number, max: number): number

A value that reverses at the edges rather than looping.

Rounding and averaging

js
import { 
mean
,
round
} from '@studiometa/js-toolkit/utils';
round
(1.2345, 2); // 1.23
mean
([1, 2, 3, 4]); // 2.5

round

ts
round(value: number, decimals?: number): number

Round to a number of decimals.

mean

ts
mean(numbers: readonly number[]): number

The arithmetic mean of a list.

Series

createRange

ts
createRange(min: number, max: number, step: number): number[]
js
import { 
createRange
} from '@studiometa/js-toolkit/utils';
createRange
(0, 1, 0.25); // [0, 0.25, 0.5, 0.75, 1]

See also

  • Easings — shaping a 0 → 1 progress
  • Motion — everything with an elapsed time

MIT Licensed