Solución
solution.tsTypeScript
// TODO: refactoriza este código — extrae constantes, mejora nombres y crea funciones auxiliares
type TypeOfCars = 'economy' | 'standard' | 'premium';
interface CarTypeFee {
type: TypeOfCars;
fee: number;
}
const ECONOMY_CAR_FEE = 35;
const STANDARD_CAR_FEE = 55;
const PREMIUM_CAR_FEE = 90;
//
const ECONOMY_CAR: CarTypeFee = {
type: 'economy',
fee: ECONOMY_CAR_FEE,
};
const STANDARD_CAR: CarTypeFee = {
type: 'standard',
fee: STANDARD_CAR_FEE,
};
const PREMIUM_CAR: CarTypeFee = {
type: 'premium',
fee: PREMIUM_CAR_FEE,
};
const CAR_TYPES = {
economy: ECONOMY_CAR,
standard: STANDARD_CAR,
premium: PREMIUM_CAR,
};
const INVALID_TYPE = -1;
//
const MIN_RENTING_DAYS = 0;
const MIN_DAYS_PER_LARGE_DISCOUNT = 14;
const MIN_DAYS_PER_REGULAR_DISCOUNT = 7;
//
const LARGE_DISCOUNT = 0.2;
const REGULAR_DISCOUNT = 0.1;
const NOT_DISCOUNT = 1;
//
const NOT_VALID_VALUE = -1;
const DAILY_INSURANCE_RATE = 15;
// TARIFA DIARIA según tipo de coche
function getDailyRate(carType: TypeOfCars) {
//
switch (carType) {
case 'economy':
return ECONOMY_CAR.fee;
case 'standard':
return STANDARD_CAR.fee;
case 'premium':
return PREMIUM_CAR.fee;
default:
return INVALID_TYPE;
}
}
// DESCUENTO, relación a aplicar al subtotal
function getDiscountRatio(rentingDays: number) {
//
if (rentingDays >= MIN_DAYS_PER_LARGE_DISCOUNT) return 1 - LARGE_DISCOUNT;
//
if (rentingDays >= MIN_DAYS_PER_REGULAR_DISCOUNT) return 1 - REGULAR_DISCOUNT;
return NOT_DISCOUNT;
}
export function calculateCarRentalCost(
rentingDays: number,
carType: TypeOfCars,
hasInsurance: boolean,
): number {
// Verificar que los días sean válidos
if (rentingDays <= MIN_RENTING_DAYS) {
return NOT_VALID_VALUE;
}
// Verificar el tipo de coche
if (!(carType in CAR_TYPES)) {
return INVALID_TYPE;
}
// Determinar la tarifa base según el tipo de auto
const RATE_PER_DAY = getDailyRate(carType);
let subTotal = RATE_PER_DAY * rentingDays;
// Aplicar descuento según los días rentados
const DISCOUNT_RATIO = getDiscountRatio(rentingDays);
let total = subTotal * DISCOUNT_RATIO;
// Agregar costo del seguro si aplica
if (hasInsurance) {
total += DAILY_INSURANCE_RATE * rentingDays;
}
return total;
}0respuestas