Solución
solution.tsTypeScript
interface DiscountRule {
threshold: number,
discount: number
}
type CarCategory = 'economy' | 'standard' | 'premium'
const MIN_ECONOMY_RATE_VALUE = 35
const MIN_STANDARD_RATE_VALUE = 55
const MIN_PREMIUM_RATE_VALUE = 90
const MIN_INSURANCE_DAYS = 15
const MIN_DAY_VALUE = 0
const RATE_BY_CAR_CATEGORY: Record<CarCategory, number> = {
'economy': MIN_ECONOMY_RATE_VALUE,
'standard': MIN_STANDARD_RATE_VALUE,
'premium': MIN_PREMIUM_RATE_VALUE
}
const MIN_DISCOUNT_THRESHOLD_ONE = 14
const MIN_DISCOUNT_THRESHOLD_TWO = 7
const DISCOUNT_VALUE_ONE = 0.2
const DISCOUNT_VALUE_TWO = 0.1
const DEFAULT_INVALID_VALUE = -1
const DISCOUNT_RULES: DiscountRule[] = [
{ threshold: MIN_DISCOUNT_THRESHOLD_ONE, discount: DISCOUNT_VALUE_ONE },
{ threshold: MIN_DISCOUNT_THRESHOLD_TWO, discount: DISCOUNT_VALUE_TWO },
]
export function calculateCarRentalCost(days: number, category: CarCategory, hasInsurance: boolean): number {
if (!isValidDay(days)) return DEFAULT_INVALID_VALUE
if (!isValidCarCategory(category)) return DEFAULT_INVALID_VALUE
const rate = calculateRateByCarCategory(category)
const subTotal = calculateDiscountForRentedDays(rate * days, days)
return hasInsurance ? subTotal + insuranceCost(days) : subTotal
}
function calculateRateByCarCategory(category: CarCategory) {
return RATE_BY_CAR_CATEGORY[category] ?? DEFAULT_INVALID_VALUE
}
function isValidDay(day: number) {
return day > MIN_DAY_VALUE
}
function calculateDiscountForRentedDays(subTotal: number, days: number) {
const discountRule = DISCOUNT_RULES.find(({ threshold }) => days >= threshold)
if (!discountRule) return subTotal
return subTotal * (1 - discountRule.discount)
}
function insuranceCost(days: number) {
return MIN_INSURANCE_DAYS * days
}
function isValidCarCategory(category: CarCategory) {
return RATE_BY_CAR_CATEGORY[category]
}2respuestas