Skip to content

Instantly share code, notes, and snippets.

@mimshins
Created July 5, 2022 11:36
Show Gist options
  • Save mimshins/04ed97a1c6301f248b23509a1be731b5 to your computer and use it in GitHub Desktop.
Save mimshins/04ed97a1c6301f248b23509a1be731b5 to your computer and use it in GitHub Desktop.
Lerp (linear interpolation), InverseLerp, and Remap functions in TypeScript
/**
* Linear interpolate on the scale given by `a` to `b`, using `t` as the point on that scale.
*/
export const lerp = (a: number, b: number, t: number) => a + t * (b - a);
/**
* Inverse Linar Interpolation, get the fraction between `a` and `b` on which `v` resides.
*/
export const inLerp = (a: number, b: number, v: number) => (v - a) / (b - a);
/**
* Remap values from one linear scale to another.
*
* `oMin` and `oMax` are the scale on which the original value resides,
* `rMin` and `rMax` are the scale to which it should be mapped.
*/
export const remap = (
v: number,
oMin: number,
oMax: number,
rMin: number,
rMax: number
) => lerp(rMin, rMax, inLerp(oMin, oMax, v));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment