Reusable remap
If you want to remap more than one value to a defined range, you may want to use this version instead.
/**
* Create a function that maps a value to a range
* @param {Number} inMin Input range minimun value
* @param {Number} inMax Input range maximun value
* @param {Number} outMin Output range minimun value
* @param {Number} outMax Output range maximun value
* @return {function} A function that converts a value
*
* @author github.com/victornpb
* @see https://mcmap.net/q/593218/-remap-or-map-function-in-javascript
*/
function createRemap(inMin, inMax, outMin, outMax) {
return function remaper(x) {
return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
};
}
Usage examples
var f2c = createRemap(32,212, 0,100); //fahrenheit to celsius
var c2f = createRemap(0,100, 32,212); //celsius to fahrenheit
f2c(-459.67) //-273.15
c2f(-273.15) //-459.6699999999999
c2f(96) //204.8
f2c(96) //35.55555555555556
f2c(60) //15.555555555555555
f2c(90) //32.22222222222222
c2f(70) //158
c2f(-30) //-22
c2f(0) //32
f2c(32) //0
var p = createRemap(0,1, 0,100);
p(0) //0
p(0.33) //33
p(0.5) //50
p(0.99) //99
p(1) //100
p(1.5) //150
p(-0.1) //-10
var map8b10b = createRemap(0,255, 0,1023);
map8b10b(0) //0
map8b10b(32) //128.3764705882353
map8b10b(64) //256.7529411764706
map8b10b(128) //513.5058823529412
map8b10b(255) //1023