Solución
solution.tsTypeScript
interface OrderItem {
price: number;
quantity: number;
}
const AMOUNT_FOR_LOW_OR_OVER_DISCOUNT = 100;
const GOLD_MEMBERSHIP_FEW_ITEMS_DISCOUNT = 0.10;
const GOLD_MEMBERSHIP_MORE_ITEMS_DISCOUNT = 0.20;
const SILVER_MEMBERSHIP_FEW_ITEMS_DISCOUNT = 0.05;
const SILVER_MEMBERSHIP_MORE_ITEMS_DISCOUNT = 0.10;
const MEMBERSHIP_TYPE_DISCOUNTPAIR: Record<"gold" | "silver", DiscountPercentagePair > = {
gold: [GOLD_MEMBERSHIP_FEW_ITEMS_DISCOUNT, GOLD_MEMBERSHIP_MORE_ITEMS_DISCOUNT],
silver: [SILVER_MEMBERSHIP_FEW_ITEMS_DISCOUNT, SILVER_MEMBERSHIP_MORE_ITEMS_DISCOUNT]
}
// Pedidos grandes reciben mayor descuento
type DiscountPercentagePair = [underControlDiscount: number, overControlDiscount : number];
export function calculateOrderDiscount(orders: OrderItem[], membershipKey: string): number {
let totalAmount = 0;
const MINIMUN_AMOUNT_FOR_DISCOUNT = 10
// Sumar el total de todos los items del pedido
for (let orderItem = 0; orderItem < orders.length; orderItem++) {
totalAmount = totalAmount + orders[orderItem].price * orders[orderItem].quantity;
}
// Verificar si el pedido cumple el mínimo requerido
if (totalAmount < MINIMUN_AMOUNT_FOR_DISCOUNT) return -1;
let discountAmount = 0;
// Aplicar descuento según el tipo de membresía y el monto total
if(MEMBERSHIP_TYPE_DISCOUNTPAIR[membershipKey]){
discountAmount = calculateDiscountAmount(totalAmount, MEMBERSHIP_TYPE_DISCOUNTPAIR[membershipKey])
}
return totalAmount - discountAmount;
}
function calculateDiscountAmount(totalAmount: number, discountPercantages: DiscountPercentagePair){
let discountAmout = 0;
if(totalAmount >= AMOUNT_FOR_LOW_OR_OVER_DISCOUNT){
discountAmout = totalAmount * discountPercantages[1];
}else {
discountAmout = totalAmount * discountPercantages[0];
}
return discountAmout
}0respuestas