What’s one of the best ways to calculate whole of a buying basket when the situation is that ,
- you probably have similar merchandise twice then buyer will get 50% low cost.
- you probably have similar merchandise 3 occasions then buyer will get 1 merchandise free of charge , Mainly purchase 2 get 1 free.
As an example ,, giving the array of fruits ..
[
Basket(productName: "Apple", productPrice: 1, productQuantity: 1),
Basket(productName: "Banana", productPrice: 2, productQuantity: 3),
Basket(productName: "Kiwi", productPrice: 3, productQuantity: 2),
]
Giving above buying basket …
Fruits Identify worth
Apple * 1 = 1
Banana * 3 = 6
Kiwi * 2 = 6
Grand whole. = 13 ..
the place the grand whole needs to be 8. I’ve seen some instance to return grand whole utilizing scale back operate the place I can return grand whole however I undecided How can I obtain it.
Code I’ve written but it surely return empty ..
struct Basket {
var productName: String
var productPrice: Int
var productQuantity: Int
}
class ShoppingCart {
var outcome: [Basket] = []
var productTotal: Double = 0
func calculateDiscountOfBasket(basket: [Basket]) -> Double {
for x in basket {
if let index = outcome.firstIndex(the place: { $0.productName == x.productName }) {
outcome[index].productQuantity += 1
} else {
outcome.append(x)
}
}
whole(basket: basket)
return productTotal
}
func whole(basket: [Basket]) {
for x in basket {
if x.productQuantity == 3 {
productTotal = outcome.scale back(0.0, { whole, product in
whole + Double((product.productQuantity * product.productPrice) - product.productPrice)
})
}
}
}
}
var productArray = [
Basket(productName: "Apple", productPrice: 1, productQuantity: 1),
Basket(productName: "Banana", productPrice: 2, productQuantity: 3),
Basket(productName: "Kiwi", productPrice: 3, productQuantity: 2),
]
var productClass = ShoppingCart()
let outcome = productClass.calculateDiscountOfBasket(basket: productArray)
print("Whole: (outcome)")