I often need a variable that has a defined min and max value. For example lets say I have the variable myVariable
it's value range can be from 5 to 20. If a value bigger then 20 is set, the value is set to 20. If a value smaller then 5 is set, the value is set to 5.
I have added a small example at the end. I use an object with a function setVal
to make sure the value is set in between the range.
Is there a way to make the use of this object easier? The best way would be:
var myValue = new MyValue(2, 20); //min , max
myValue = 40; //myValue is set to 20
myValue = 15; //myValue is set to 15
myValue = -111; //myValue is set to 2
I am just not sure if this is possible?
Also what is the most performant way to solve this? (As I will use this at a lot of places and will change the values a lot).
And here the example mentioned above of a working example:
function MyValue(min, max) {
this.val = 0;
this.min = min;
this.max = max;
this.setVal = function(v) {
if(v < min) {
this.val= min;
} else if(v > max) {
this.val = max;
} else {
this.val = v
}
}
}
//tests
myvalue = new MyValue(2, 10); //create New MyValue with min = 2, max = 10
myvalue.setVal(5); //set 5, 5 is within the range
console.log(myvalue.val); //output: 5
myvalue.setVal(12); //set 12, 12 is outside the range
console.log(myvalue.val); //output 10
myvalue.setVal(1); //set 1, 1 is outside the range
console.log(myvalue.val); //output 2
myvalue.setVal(-25); //set -25, -25 is outside the range
console.log(myvalue.val); //output 2