There are 2 select fields, each of which has 18 values, from 1 to 18.

Now I have a calculator that is very simple - it calculates the difference between the past and the current value and multiplies it by 100:

var current_rank, new_rank; $('#rank1').change(function(){ current_rank = parseInt($(this).val()); var result = (new_rank - current_rank) * 100; console.log(result); }); $('#rank2').change(function(){ var new_rank = parseInt($(this).val()); var result = (new_rank - current_rank) * 100; console.log(result); }); 

But then the question arose: How to make coefficients for these values? Those. To from 1 to 6 the price was 100, from 7 to 12 - 300 and from 13 to 18 - 500?

For examples, to make it clearer: A person chooses from the first field a value of 3, from 2 fields a value of 6. All values ​​are in the range from 1 to 6, therefore, (6-3) * 100 = 300.

The value of 1 field is 5, the value of 2 field is 9 Now it happens like this: (9-5) * 100 = 400, but I need it to be calculated in a different way, because this includes the value 6, the price of which is 100, and also the values ​​7 8 and 9, the price of which is 300. Therefore, the result will be as follows: 100+ (300 * 3) = 1000

How to do it, who knows? But even there are no thoughts, although everything seems to be just ...

    1 answer 1

    The simplest solution would be to count all this in a cycle:

     function diffRank(prev, curr) { let res = 0; for (let i = curr; i > prev; i--) { switch (true) { case i >= 13: res += 500; break; case i >= 7: res += 300; break; default: res += 100; } } return res; } 

    However, you can try to solve this analytically:

     res += (curr - prev) * 100; if (curr>6 ) res+= (curr-6) * 200; if (curr>12 ) res+= (curr-12) * 200; 

    If you take advantage of how bool expressions are reduced to numeric, you can write this one-liner write-only:

     const diffRate = (p, c) => 100*((cp)+2*((c>6)*(c-6)+(c>12)*(c-12))); console.log(diffRate(5, 9)); console.log(diffRate(5, 14)) 

    • Yes, thanks, I am already doing a loop :) - Alexxosipov
    • Do you think this is the right way to do this: Made the object ranks = { 1: 100, 2: 200, 3: 300, 4: 400, 5: 500, 6: 600, 7: 700, 8: 800, 9: 900, 10: 1000, 11: 1100, 12: 1200, 13: 1300, 14: 1400, 15: 1500, 16: 1600, 17: 1700, 18: 1800}; And from it I pull out values ​​on a cycle? Or do not do that? - Alexxosipov
    • Why such an object? This is just a mapping i => 100*i - vp_arth
    • But if it is necessary for each wound to register its price and add it to the final result, then what to do? - Alexxosipov
    • If so, then yes, fine. - vp_arth