Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Price Calculation Tool

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!

like image 969
Benjiman Avatar asked Jul 22 '26 11:07

Benjiman


1 Answers

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))
like image 172
AZ_ Avatar answered Jul 24 '26 03:07

AZ_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!