Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
How to combine map and clamp function together

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!