Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a map function in vanilla javascript like p5.js? [duplicate]

In p5.js, theres a function called map() which maps a value in a certain range to another value in another range. Is there a similar method like this in vanilla javascript?

like image 444
Plzhelp Avatar asked Oct 30 '25 01:10

Plzhelp


1 Answers

No, there isn't anything like that in JavaScript out of the box, but it's easy enough to write your own:

// linearly maps value from the range (a..b) to (c..d)
function mapRange (value, a, b, c, d) {
    // first map value from (a..b) to (0..1)
    value = (value - a) / (b - a);
    // then map it from (0..1) to (c..d) and return it
    return c + value * (d - c);
}

Also, P5.js is written in JavaScript, so its map() function is vanially JavaScript. P5.js is open-source, and the map() function can be found here:

var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2;
like image 81
2 revs, 2 users 80%Ilmari Karonen Avatar answered Nov 01 '25 16:11

2 revs, 2 users 80%Ilmari Karonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!