inverseLerp function
Computes where a value sits between two numbers: the inverse of lerp. Not clamped.
ts
import { inverseLerp } from 'utils';Signature
ts
export function inverseLerp(start: number, end: number, value: number): numberParameters
| Name | Description |
|---|---|
start | The value mapped to 0. |
end | The value mapped to 1. |
value | The value to locate. |
Returns
The interpolation factor; 0 when start === end.
Example
ts
inverseLerp(0, 10, 5); // 0.5
inverseLerp(10, 0, 2.5); // 0.75Tests
Line coverage: 100 %.
- ✅ places 0 → 10 at 5 as 0.5
- ✅ places 10 → 0 at 5 as 0.5
- ✅ places 0 → 10 at 20 as 2
- ✅ places 5 → 5 at 5 as 0
- ✅ places 5 → 5 at 100 as 0
Source
src/math/inverse-lerp.ts (on GitHub)
Used by
remap: Maps a value from an input range to an output range, such as a sensor reading to a gauge angle.
Source code
ts
/**
* Computes where a value sits between two numbers: the inverse of `lerp`. Not clamped.
*
* @param start - The value mapped to 0.
* @param end - The value mapped to 1.
* @param value - The value to locate.
* @returns The interpolation factor; `0` when `start === end`.
* @example
* inverseLerp(0, 10, 5); // 0.5
* inverseLerp(10, 0, 2.5); // 0.75
*/
export function inverseLerp(start: number, end: number, value: number): number {
const span = end - start;
return span === 0 ? 0 : (value - start) / span;
}Test file
ts
import { inverseLerp } from './inverse-lerp';
describe(inverseLerp, () => {
it.for([
[0, 10, 5, 0.5],
[10, 0, 5, 0.5],
[0, 10, 20, 2],
[5, 5, 5, 0],
[5, 5, 100, 0],
] as const)('places %s → %s at %s as %s', ([start, end, value, expected]) => {
expect(inverseLerp(start, end, value)).toBe(expected);
});
});Keywords: inverse, lerp, math, function