Scaling values between two ranges
In some cases, you have one type of value with a specific range and you want to scale them proportionally into a new range.
function scale(value, inMin, inMax, outMin, outMax) {
const result = (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
if (result < outMin) {
return outMin;
} else if (result > outMax) {
return outMax;
}
return result;
}
If you have a lot of places where you need to scale values between the same two ranges a class might be more useful to reduce repeating the min/max properties each time.
class Scaler {
constructor(inMin, inMax, outMin, outMax) {
this.inMin = inMin;
this.inMax = inMax;
this.outMin = outMin;
this.outMax = outMax;
}
scale(value) {
const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;
if (result < this.outMin) {
return this.outMin;
} else if (result > this.outMax) {
return this.outMax;
}
return result;
}
}
I added boundary constraints as the names of the arguments outMin
and outMax
inclines that the output value must always stay within that range. Feel free to throw errors or return ǸaN
instead for those cases if any of those are your preferred way to handle bad values.
Happy scaling!