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?
Asked
Active
Viewed 2,656 times
3
-
3@xander: That's not [the kind of map the OP wants](https://p5js.org/reference/#/p5/map). – Ilmari Karonen Feb 15 '18 at 08:40
-
@IlmariKaronen you're right, but an example in the question would have helped I guess. And it's pretty simple to implement a range mapping like that in a simple way. – xander Feb 15 '18 at 08:42
-
1Check [Javascript / jQuery - map a range of numbers to another range of numbers](https://stackoverflow.com/questions/10756313/javascript-jquery-map-a-range-of-numbers-to-another-range-of-numbers). – user2314737 Feb 15 '18 at 08:45
1 Answers
7
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;

Kevin Workman
- 41,537
- 9
- 68
- 107

Ilmari Karonen
- 49,047
- 9
- 93
- 153