remap function
Maps a value from an input range to an output range, such as a sensor reading to a gauge angle. Inverted ranges work.
ts
import { remap } from 'utils';Signature
ts
export function remap(
value: number,
inMin: number,
inMax: number,
outMin: number,
outMax: number,
shouldClamp = false,
): numberParameters
| Name | Description |
|---|---|
value | The value to map. |
inMin | The input mapped to outMin. |
inMax | The input mapped to outMax. |
outMin | The output for inMin. |
outMax | The output for inMax. |
shouldClamp | Whether to keep the result within the output range. Defaults to false. |
Returns
The mapped value; outMin when the input range is empty.
Example
ts
remap(5, 0, 10, 0, 100); // 50
remap(15, 0, 10, 0, 100, true); // 100Tests
Line coverage: 100 %.
- ✅ maps between ranges
- ✅ extrapolates unless the output is clamped
- ✅ returns outMin for an empty input range
Source
src/math/remap.ts (on GitHub)
Uses
clamp: Restricts a number to an interval.inverseLerp: Computes where a value sits between two numbers: the inverse oflerp.lerp: Interpolates linearly between two numbers, exact at both ends and extrapolated outside [0, 1].
Files it needs
src/math/remap.ts imports, directly or not:
Source code
ts
import { clamp } from './clamp';
import { inverseLerp } from './inverse-lerp';
import { lerp } from './lerp';
/**
* Maps a value from an input range to an output range, such as a sensor reading to a gauge angle. Inverted
* ranges work.
*
* @param value - The value to map.
* @param inMin - The input mapped to `outMin`.
* @param inMax - The input mapped to `outMax`.
* @param outMin - The output for `inMin`.
* @param outMax - The output for `inMax`.
* @param shouldClamp - Whether to keep the result within the output range. Defaults to `false`.
* @returns The mapped value; `outMin` when the input range is empty.
* @example
* remap(5, 0, 10, 0, 100); // 50
* remap(15, 0, 10, 0, 100, true); // 100
*/
export function remap(
value: number,
inMin: number,
inMax: number,
outMin: number,
outMax: number,
shouldClamp = false,
): number {
const t = inverseLerp(inMin, inMax, value);
return lerp(outMin, outMax, shouldClamp ? clamp(t) : t);
}Test file
ts
import { remap } from './remap';
describe(remap, () => {
it('maps between ranges', () => {
expect(remap(5, 0, 10, 0, 100, false)).toBe(50);
expect(remap(5, 0, 10, 100, 0, false)).toBe(50);
expect(remap(2, 0, 10, 100, 200, false)).toBe(120);
});
it('extrapolates unless the output is clamped', () => {
expect(remap(15, 0, 10, 0, 100, false)).toBe(150);
expect(remap(15, 0, 10, 0, 100, true)).toBe(100);
expect(remap(-5, 0, 10, 0, 100, true)).toBe(0);
});
it('returns outMin for an empty input range', () => {
expect(remap(3, 1, 1, 0, 100, false)).toBe(0);
});
});Keywords: remap, math, function