skip to Main Content

I’m trying to write a function to return a certain value if the input is between a certain number range.

Normally, I would just write a series of if/else if statements to do the job. But, I’m working with a large number of ranges so writing out 30+ if/else if statements seems inefficient.

Let’s say I have a set min and max number for the overall range and I want to break that up into smaller ranges. For each range, I want to return some value. Ideally, the return value for each range will decrease by some set number.

For context, I’m trying to use something similar to this to calculate a value based on mileage. For example, if the mileage is between 101-120 miles, the rate is equal to 80% of the mileage. As the mileage increases, the percentage decreases. And, the number that the percentage decreases by can be some set number (-0.05 for example)

...
else if (m >= 101 && m <= 120) return 0.80
else if (m >= 121 && m <= 140) return 0.75
...

Since there is a pattern to the return values for each range, I’m thinking this can be done in a better way than just writing out a bunch of if/else statements but I’m not sure exactly how that can be done. Any ideas?

2

Answers


  1. Your example doesnt increment by 15; so, I’m assuming that was a typo.

    The solution I would use is a function.
    ie.

    (() => {
    
    // in your example you have it .95 -> .9 -> .85 thus this starts at 1.
    const STARTING_RETURN_VALUE = 1;
    
    // the range increment your if statement has is 15
    const INCREMENT = 15;
    
    // this is the value in which the return value decreases by per interval
    const DECREASING_RETURN_VALUE = .05;
    
    const getReturn = (x, increment, starting_return_value, decreasing_return_value) => {
         return starting_return_value - (Math.floor(x/increment)+1)*decreasing_return_value;
    }
    
    console.log(getReturn(29, INCREMENT, STARTING_RETURN_VALUE, DECREASING_RETURN_VALUE));
    
    })();
    Login or Signup to reply.
  2. something like that ?

    console.log('112->', computeRate( 0.95, 0.05, 100, 20, 112 )); // 0,9
    console.log('133->', computeRate( 0.95, 0.05, 100, 20, 133 )); // 0,85
    console.log('164->', computeRate( 0.95, 0.05, 100, 20, 164 )); // 0,75
    console.log('250->', computeRate( 0.95, 0.05, 100, 20, 250 )); // 0,55 
    
    
    function computeRate( base, baseDec, toptest, step, value )
      {
      let min  = 0
        , max  = toptest
        , resp = base
        ;
      while ( (!(value >= min && value <= max)) && resp > 0)
        {
        min  += step; // min += step +1;  is not necessary;
        max  += step;
        resp -= baseDec;
        resp = resp.toFixed(2);  // to fix float numbers matters
        }
      return Number.parseFloat(resp);
      }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search