Reputation: 31
I'm trying to make a tool for a price calculation. The reduction on some of the options is a bit complicated and i'm stuck on how to translate this to code. There are 4 different products: Product 1: €10 Product 2: €20 Product 3: €30 Product 4: €40
For Product 1 and Product 2 there is no reduction.
If you buy 2 or more of Product 3, the price reduces to €21.
If you buy 2 or more of Product 4, the price reduces to €31.
If you buy Product 3 and Product 4 together, the price reduces to €21 and €31 for the products respectively.
Can you guys help me out on how I should go about translating this to javascript (or another language if you think there's a better solution)?
Thanks a lot!
Upvotes: 3
Views: 98
Reputation: 12152
Use objects to store prices and values
var obj={P1:10,P2:20,P3:30,P4:40};
var basket={P1:5,P2:4,P3:3,P4:8};
var total=0;
obj['P3']>=2?obj['P3']=21:false;
obj['P4']>=2?obj['P4']=31:false;
if(obj['P3']>=1 && obj['P4']>=1)
{
obj['P3']=21;
obj['P4']=31;
}
Object.keys(basket).forEach(e=>{
total+=basket[e]*obj[e];
})
console.log(total)
Product 1: €10 Product 2: €20 Product 3: €30 Product 4: €40
For Product 1 and Product 2 there is no reduction.
If you buy 2 or more of Product 3, the price reduces to €21.
If you buy 2 or more of Product 4, the price reduces to €31.
If you buy Product 3 and Product 4 together, the price reduces to €21 and €31 for the products respectively.
Upvotes: 1
Reputation: 3132
You can create a relation for product and price Object/Map
When calculating the basket price update the product prices as per defined rules.
let products = {
p1: 10,
p2: 20,
p3: 30,
p4: 40
}
let priceCalculate = (basket) => {
let disPrices = { ...products }
if (basket.filter(e => e === 'p3').length >= 2) disPrices.p3 = 21
if (basket.filter(e => e === 'p4').length >= 2) disPrices.p4 = 31
if (basket.includes('p3') && basket.includes('p4')) disPrices.p3 = 21, disPrices.p4 = 31
return basket.reduce((a, b) => a + disPrices[b], 0);
}
let Mybasket = ['p1', 'p2', 'p3', 'p2', 'p3'];
console.log(priceCalculate(Mybasket))
Upvotes: 1