Search code examples
javascriptfrontendlogicjavascript-objectsmodulo

Check quantity of item and append correct price either Sales price or Regular price based on sales variable


The task is to build an accurate price calculator which accounts for a sales price based on quantity. I've built a gross price calculator using compiledCart.reduce() method, (below) however I can't figure out how to add the sales functionality.

If the user buys 1 Candy, the price is $3.97, if the user buys 2, the price is $5.00. If the user buys 3, then first two are $5.00 and the 3rd is $3.97. Same thing if the user buys 5. The first 4 are $10 and the 5th one is $3.97

My compiledCart variable looks like this:

    [ 
     0: {item: "candy", quantity: 3, price: 3.97, salesPrice: 5.00}, 
     1: {item: "bread", quantity: 1, price: 2.17} 
    ]

This is what I'm doing to get the gross:

    const gross = compiledCart.reduce( ( sum, { price, quantity } ) => sum + (price * quantity) , 0)

But I can't for the life of me figure out how to factor in the sales price variable.

I tried using the modulous % operator like this:

    quantity % 2

But that only returns a 1 or 0 based on if there is a reminder. So 2 candies in the cart will return a 0 while 1 candy will return a 1 since 1 / 2 = 1. But I'm not sure how I can use that for my cause?


Solution

  • Try this

    const gross = cart.reduce((sum, {price, quantity, salesPrice = 0}) => {
        let total = 0;
        if (quantity >= 2) {
            const saleQuantity = 2 * Math.floor(quantity / 2);
            console.log({saleQuantity, remainderQuantity: quantity - saleQuantity});
            total = ((saleQuantity / 2) * salesPrice) + (price * (quantity - saleQuantity));
        } else {
            total = (price * quantity);
        }
        return sum + total;
    }, 0);