Skip to content

Instantly share code, notes, and snippets.

@umaar
Forked from fpillet/scale.js
Created March 31, 2021 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save umaar/039d09aa5ac75bc2b808083500c6d166 to your computer and use it in GitHub Desktop.
Save umaar/039d09aa5ac75bc2b808083500c6d166 to your computer and use it in GitHub Desktop.
Javascript value scaling between two ranges
/* Scale a value from one range to another
* Example of use:
*
* // Convert 33 from a 0-100 range to a 0-65535 range
* var n = scaleValue(33, [0,100], [0,65535]);
*
* // Ranges don't have to be positive
* var n = scaleValue(0, [-50,+50], [0,65535]);
*
* Ranges are defined as arrays of two values, inclusive
*
* The ~~ trick on return value does the equivalent of Math.floor, just faster.
*
*/
function scaleValue(value, from, to) {
var scale = (to[1] - to[0]) / (from[1] - from[0]);
var capped = Math.min(from[1], Math.max(from[0], value)) - from[0];
return ~~(capped * scale + to[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment