Home > Blockchain >  How to combine map and clamp function together
How to combine map and clamp function together

Time:12-28

There are two functions

const clamp = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a)   c

const c = map(-50, 0, 1, 0, 100)
const _c = clamp(c, 0, 1)
console.log(_c, c)

Is there any way that the two function could be combined, something like

const _c = map(-50, 0, 1, 0, 100, {clamp: true})

so that I don't need copy parameters from the map function to get the new value within the parameters range.

CodePudding user response:

It is pretty easy, just create a single function and that sequentially executes the original map function and if the clamp parameter is true then compute that and return it. Check below for the code.

const map(x, a, b, c, d, clamp) {
   const map_result = (x - a) * (d - c) / (b - a)   c;
   if (clamp) {
       const clamp_result = Math.max(Math.min(map_result, Math.max(a, b)), Math.min(a, b));
       return clamp_result
   }

   return map_result;
}

You can use it like this: const _c = map(-50, 0, 1, 0, 100, true)

CodePudding user response:

You can pass the function to the clamp function and use it inside the same. Or if the functions are in same location you can just invoke it inside the clamp function

const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a)   c


 
const _map = (x, a, b, c, d, map) =>  Math.max(Math.min(map(x, a, b, c, d), Math.max(a, b)), Math.min(a, b));


const a =  _map(-50, 0, 1, 0, 100, map)
console.log(a)

  • Related