-1

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
nbar
  • 6,028
  • 2
  • 24
  • 65
  • This is essentially a dupe of https://stackoverflow.com/questions/44103234/how-to-intercept-a-known-property-value-assignment-of-an-unknwon-object-created –  Jul 18 '19 at 13:11
  • @ChrisG Hmm so the idea is to use the prototype, give min max with the constructor, and then overwrite set method and then compare the given value with this min max values? – nbar Jul 18 '19 at 13:14
  • Not sure about that, my point was that intercepting `myValue = 40;` isn't possible. –  Jul 18 '19 at 13:15

2 Answers2

1

This is one way of what you're trying to do

function getMinMaxValue(min, max) {
  let value
  return {
    get current() {
      return value
    },
    set current(val) {
      if (val > max) value = max
      else if (val < min) value = min
      else value = val
    }
  }
}

const value = getMinMaxValue(5, 20)

value.current = 1

console.log(value.current)
Prithwee Das
  • 4,628
  • 2
  • 16
  • 28
0

You need a closure to emulate private variable:

function MyValue(min, max) {
  let value;

  return {
    get() {
      return value;
    },
    set(newValue) {
      value = (newValue < min) ? min : (newValue > max) ? max : newValue;  
    }
  };
}

const value = new MyValue(1, 10)

value.set(5);
value.get(); // 5

value.set(600);
value.get(); // 10
Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47