Skip to content

Instantly share code, notes, and snippets.

@victorloux
Created October 4, 2016 15:49
Show Gist options
  • Save victorloux/8976fcfafc158480b672d30e41ead053 to your computer and use it in GitHub Desktop.
Save victorloux/8976fcfafc158480b672d30e41ead053 to your computer and use it in GitHub Desktop.
/*
* Re-maps a number from one range to another, akin to map() in Processing and Arduino
*
* @param {Number} value The number to map
* @param {Number} inMin The lower bound of the value's current range
* @param {Number} inMax The upper bound of the value's current range
* @param {Number} outMin The lower bound of the value's target range
* @param {Number} outMax The upper bound of the value's target range
* @param {boolean} capped Set to true to cap to the min/max target range, even if the input was outwith the current range
*
* @return {Number} The mapped value
*/
mapTo = function(value, inMin, inMax, outMin, outMax, capped) {
var newVal = (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
if (capped !== null && capped) {
return Math.max(outMin, Math.min(newVal, outMax));
}
return newVal;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment