Reputation: 117
I am struggling with simple problem. What is elegant way of achieving this.
I have 2 values minimum and maximum which can be positive or negative and a third value which is between them. Now I want to calculate position(percentage)
of other given number, which in my case is the width of element.
For example here I want to find what is position in the range 0-200 that represents value -10 in range -500 to 600 ?
var min = -500;
var max = 600;
var value = -10;
var width = 200;
var positionInWidth = ???;
Upvotes: 2
Views: 854
Reputation: 276306
You can one-liner this but let's do this in a few steps to see how it works:
// first we get the total range
var length = max - min; // 1100
// then we offset the position by the start position
var positionInLength = value - min; // 490
// now we get the percent through the value is in the position
var valuePercent = positionInLength / length;
// or a one liner (value - min) / (max - min);
// Then finally, apply `width percentage`
const positionInWidth = width * valuePercent;
Or as a one liner:
const positionInWidth = width * ((value - min) / (max - min));
Upvotes: 4
Reputation: 21
So if I understand the question correctly, you are looking for the so called map function. If that's the case, the implementation is as given:
function map(input, inMin, inMax, outMin, outMax) {
return (input - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}
In your scenario outMin = 0:
console.log(map(-10, -500, 600, 0, 200)); // === 89.0909090909091
Upvotes: 1