Remap or Map function in Javascript

后端 未结 5 1974
小鲜肉
小鲜肉 2020-12-08 11:26

Of late, most of my programming experience has been in Processing, and more recently I have been wanting to branch out a little deeper in to some JavaScript, since they are

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 11:38

    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 Victor N. wwww.victorborges.com
     * @see https://gist.github.com/victornpb/51b0c17241ea483dee2c3a20d0f710eb/
     */
    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
    

提交回复
热议问题