Skip to content

Instantly share code, notes, and snippets.

@aarongeorge
Last active November 30, 2020 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarongeorge/d39dec45eb76496d99e77463cb1fa0c4 to your computer and use it in GitHub Desktop.
Save aarongeorge/d39dec45eb76496d99e77463cb1fa0c4 to your computer and use it in GitHub Desktop.
Linear remapping in JavaScript. When n, a and b are equal, x will be returned instead of NaN (Due to divide by zero)
const remap = (n, a, b, x, y) => x + (y - x) * (n - a) / (b - a) || x
/*
Usage:
n = Number
a = from lower bound
b = from upper bound
x = to lower bound
y = to upper bound
Note:
Will return `x` if `n`, `a` and `b` are equal
*/
remap(5, 0, 10, 0, 1) // Returns 0.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment