Solución
solution.tsTypeScript
// TODO: refactoriza este código — extrae constantes, mejora nombres y crea funciones auxiliares
const DAILY_RATE_BY_CAR_TYPE = {
economy: 35,
standard: 55,
premium: 90
} as const
type CarType = keyof typeof DAILY_RATE_BY_CAR_TYPE
const SHORT_RENTAL_DISCOUNT = 0.1
const LONG_RENTAL_DISCOUNT = 0.2
const INSURANCE_DAILY_PRICE = 15
function applyRentalDiscount(totalCost: number, rentalDays: number): number {
if (rentalDays >= 14) {
return totalCost * (1 - LONG_RENTAL_DISCOUNT)
} else if (rentalDays >= 7) {
return totalCost * (1 - SHORT_RENTAL_DISCOUNT)
}
return totalCost
}
function isValidCarType(carType: unknown): carType is CarType {
return (
typeof carType === 'string'
&& carType in DAILY_RATE_BY_CAR_TYPE
)
}
export function calculateCarRentalCost(days: number, carType: CarType, hasInsurance: boolean): number {
// Verificar que los días sean válidos
if (days <= 0) return -1;
if (!isValidCarType(carType)) return -1
// Determinar la tarifa base según el tipo de auto
const dailyRate = DAILY_RATE_BY_CAR_TYPE[carType];
// Aplicar descuento según los días rentados
const baseCost = dailyRate * days;
let totalCost = applyRentalDiscount(baseCost, days)
// Agregar costo del seguro si aplica
if (hasInsurance) {
totalCost += INSURANCE_DAILY_PRICE * days;
}
return totalCost;
}
0respuestas