Calculate costs by quantity with javascript

I can’t finish it. I know how to find out if a number is divisible by 3, but as soon as I get above 3, how to keep the discount plus the remainder? Example: 7 tickets cost $ 120

$ 20 each or 3 for $ 50

<input id="raffleTix" type="text" value="0" />
if($('#raffleTix').val() % 3 == 0){
    raffle = ($('#raffleTix').val() / 3) * 50;
}else if($('#raffleTix').val() < 3){
    raffle = $('#raffleTix').val() * 20;
}else{

}
+4
source share
1 answer

There is no need to have conditional logic. This can be done using a simple formula:

var value = $('#raffleTix').val();
var setsOfThree = Math.floor(value / 3);
var singles = value - setsOfThree * 3;

raffle = setsOfThree * 50 + singles * 20;

Or even better, all this could be put into a function, so that you could pass different values ​​without changing the code:

function computeCost(quantity, setSize, setCost, singleCost) {
    var sets = Math.floor(quantity / setSize);
    var singles = quantity - sets * setSize;

    return sets * setCost + singles * singleCost;
}

raffle = computeCost($('#raffleTix').val(), 3, 50, 20);
+3
source

Source: https://habr.com/ru/post/1611651/


All Articles