Solución
solution.tsTypeScript
const INVALID_INPUT_RESULT = -1;
const LOCAL_ZONE = 'local';
const REGIONAL_ZONE = 'regional';
const NATIONAL_ZONE = 'nacional';
const LOCAL_BASE_RATE_PER_KG = 2;
const REGIONAL_BASE_RATE_PER_KG = 5;
const NATIONAL_BASE_RATE_PER_KG = 10;
const LOCAL_DISTANCE_SURCHARGE_RATE = 0.10;
const REGIONAL_DISTANCE_SURCHARGE_RATE = 0.05;
const NATIONAL_DISTANCE_SURCHARGE_RATE = 0.02;
const HEAVY_PACKAGE_WEIGHT_THRESHOLD = 20;
const HEAVY_PACKAGE_DISCOUNT_MULTIPLIER = 0.90;
const ROUNDING_FACTOR = 100;
export function calculateShippingCost(
weight: number,
distance: number,
zone: string
): number {
if (!isValidInput(weight, distance)) {
return INVALID_INPUT_RESULT;
}
const { baseCost, distanceSurcharge } = calculateZoneCosts(
weight,
distance,
zone
);
let totalCost = baseCost + distanceSurcharge;
if (weight > HEAVY_PACKAGE_WEIGHT_THRESHOLD) {
totalCost *= HEAVY_PACKAGE_DISCOUNT_MULTIPLIER;
}
return Math.round(totalCost * ROUNDING_FACTOR) / ROUNDING_FACTOR;
}
function isValidInput(weight: number, distance: number): boolean {
return weight > 0 && distance > 0;
}
function calculateZoneCosts(
weight: number,
distance: number,
zone: string
): { baseCost: number; distanceSurcharge: number } {
if (zone === LOCAL_ZONE) {
return {
baseCost: weight * LOCAL_BASE_RATE_PER_KG,
distanceSurcharge: distance * LOCAL_DISTANCE_SURCHARGE_RATE,
};
}
if (zone === REGIONAL_ZONE) {
return {
baseCost: weight * REGIONAL_BASE_RATE_PER_KG,
distanceSurcharge: distance * REGIONAL_DISTANCE_SURCHARGE_RATE,
};
}
if (zone === NATIONAL_ZONE) {
return {
baseCost: weight * NATIONAL_BASE_RATE_PER_KG,
distanceSurcharge: distance * NATIONAL_DISTANCE_SURCHARGE_RATE,
};
}
return {
baseCost: 0,
distanceSurcharge: 0,
};
}0respuestas