Solución
solution.tsTypeScript
type ProductCategory = 'electronics' | 'clothing' | 'food';
const PRODUCTS = {
electronics: {discount: 0.15},
clothing: {discount: 0.2},
food: {discount: 0.05},
others: {discount: 0},
};
const IVA_21 = 0.21;
const NON_VALID = -1;
function getTypeOfDiscount(
productCategory: ProductCategory,
price: number,
): number {
//
const discount = PRODUCTS[productCategory]?.discount;
//
if( !discount ) return PRODUCTS['others'].discount;
return price * discount;
}
export function getProductFinalPrice(
price: number,
productCategory: ProductCategory,
stock: number,
): number {
// Verificar si el stock es válido
if (stock <= 0) return NON_VALID;
// Verificar si el precio es válido
if (price <= 0) return NON_VALID;
// Aplicar descuento según la categoría del producto
const DISCOUNT = getTypeOfDiscount(productCategory, price);
// Calcular el precio con descuento aplicado
let discounted = price - DISCOUNT;
// Aplicar el impuesto sobre el precio con descuento
let result = discounted * (1 + IVA_21);
// Redondear a dos decimales
return Math.round(result * 100) / 100;
}0respuestas