In JavaScript, a range of values can be mapped from one range to another using mathematical formulas. For example, a value from 0–100 can be mapped to a target range such as 100–10,000,000.
- The input range represents the values provided by the slider.
- The output range represents the values to which the input is mapped.
- A logarithmic scale can be used when the target range covers very large values.
- Mathematical formulas can also be used to perform the mapping.
Approach 1: Using a Logarithmic Scale
In this approach, the logarithmic values of the target range are calculated first. The scale is then determined using the difference between the logarithmic limits. Finally, Math.exp() is used to convert the logarithmic result back to the original scale.
Syntax:
Math.exp(minValue + scale * (position - minPosition));Example: This example maps a value from the range 0–100 to the range 100–10,000,000 using a logarithmic scale.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Range Mapping</title>
</head>
<body style="text-align:center;">
<h1>GeeksForGeeks</h1>
<h3>
Create slider to map a range of values
</h3>
<p id="GFG_UP"></p>
<button onclick="myGFG()">
Click Here
</button>
<p id="GFG_DOWN"></p>
<script>
let up = document.getElementById("GFG_UP");
let val = 50;
up.innerHTML = "Click on the button to map "
+ "the value (0-100) to a range from "
+ "100 to 10,000,000<br>Value - " + val;
let down = document.getElementById("GFG_DOWN");
function Slider(pos) {
let minM = 0;
let maxM = 100;
let minV = Math.log(100);
let maxV = Math.log(10000000);
let scal = (maxV - minV) / (maxM - minM);
return Math.exp(minV + scal * (pos - minM));
}
function myGFG() {
down.innerHTML = "The value for "
+ val + " is " + Slider(val);
}
</script>
</body>
</html>
Approach 2: Using a Mathematical Formula
In this approach, a mathematical formula is used to map the input value to the required range. The formula uses Math.exp() to produce values on a logarithmic scale.
Example: This example maps the value 50 from the range 0–100 to the target range using a mathematical formula.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Range Mapping</title>
</head>
<body style="text-align:center;">
<h1>GeeksForGeeks</h1>
<h3>
Create slider to map a range of values in JavaScript
</h3>
<p id="GFG_UP"></p>
<button onclick="myGFG()">
Click Here
</button>
<p id="GFG_DOWN"></p>
<script>
let up = document.getElementById("GFG_UP");
let val = 50;
up.innerHTML = "Click on the button to map "
+ "the value (0-100) to a range from "
+ "100 to 10,000,000<br>Value - " + val;
let down = document.getElementById("GFG_DOWN");
function Slider(pos) {
return Math.floor(
-900 + 1000 * Math.exp(pos / 10.857255959)
);
}
function myGFG() {
down.innerHTML = "The value for "
+ val + " is " + Slider(val);
}
</script>
</body>
</html>