search

Home  >  Q&A  >  body text

A smarter approach would be to write a function that uses many conditional statements to return incremental values ​​based on different numerical ranges

<p>I'm trying to write a function that returns a specific value if the input is within a certain range of numbers. </p> <p>Normally, I would write a series of if/else if statements to accomplish this task. However, I'm dealing with a large number of ranges, so writing out 30+ if/else if statements seems inefficient. </p> <p>Suppose I have a minimum and maximum number for an overall range, and I want to split it into smaller ranges. For each range I want to return some values. Ideally, the return value for each range would be decremented by some fixed number. </p> <p>To provide context, I'm trying to calculate a value based on mileage using something like this. For example, if the mileage is between 101-120 miles, the rate is equal to 80% of the mileage. The percentage decreases as mileage increases. Moreover, the value of the percentage decrease can be a fixed number (such as <code>-0.05</code>)</p> <pre class="brush:php;toolbar:false;">... else if (m >= 101 && m <= 120) return 0.80 else if (m >= 121 && m <= 140) return 0.75 ...</pre> <p>Since there is a pattern in the return value for each range, I think it can be done in a better way than writing a bunch of if/else statements, but I'm not sure exactly how. Any ideas? </p>
P粉311464935P粉311464935549 days ago576

reply all(1)I'll reply

  • P粉930534280

    P粉9305342802023-08-18 10:53:55

    Your example does not increment by 15; so, I'm assuming that's a typo.

    I will use a function to solve it. For example:

    (() => {
    
    // 在你的例子中,你有 .95 -> .9 -> .85,因此这从1开始。
    const STARTING_RETURN_VALUE = 1;
    
    // if语句中的递增范围是15
    const INCREMENT = 15;
    
    // 这是每个间隔中返回值递减的值
    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));
    
    })();

    reply
    0
  • Cancelreply