Solución

@isakidev·12/5/2026TypeScript
solution.tsTypeScript
type ProductCategory = 'electronics' | 'clothing' | 'food'

interface ProductDiscountResult {
  price: number
  discount: number
  totalWithDiscount: number
}

const ERROR_RESULT: number = -1
const DEFAULT_RATE: number = 0

const MIN_VALID_STOCK: number = 1
const MIN_VALID_PRICE: number = 1

const TAX_RATE: number = 1.21

const ELECTRONICS_RATE: number = 0.15
const CLOTHING_RATE: number = 0.20
const FOOD_RATE: number = 0.05

const DISCOUNT_BY_PRODUCT_CATEGORY: Record<ProductCategory, (price: number) => number> = {
  electronics: (price: number) => price * ELECTRONICS_RATE,
  clothing: (price: number) => price * CLOTHING_RATE,
  food: (price: number) => price * FOOD_RATE
}

export function getProductFinalPrice(price: number, category: ProductCategory, stock: number): number {
  if (!isValidProductStock(stock)) return ERROR_RESULT
  if (!isValidProductPrice(price)) return ERROR_RESULT

  const { totalWithDiscount } = calculateDiscountByProductCategory(category, price)

  const total = applyTax(totalWithDiscount)

  return roundToDecimals(total)
}

function isValidProductStock(stock: number): boolean {
  return stock >= MIN_VALID_STOCK
}

function isValidProductPrice(price: number): boolean {
  return price >= MIN_VALID_PRICE
}

function calculateDiscountByProductCategory(category: ProductCategory, price: number): ProductDiscountResult {
  const rule = DISCOUNT_BY_PRODUCT_CATEGORY[category]
  const discount = rule ? rule(price) : DEFAULT_RATE

  const totalWithDiscount = price - discount

  return { discount, price, totalWithDiscount }
}

function applyTax(total: number): number {
  return total * TAX_RATE
}

function roundToDecimals(value: number): number {
  return Math.round(value * 100) / 100;
}
0respuestas
Respuestas

Aún no hay respuestas

¡Sé el primero en responder!

Escribir un comentario

Recuerda ser amable. Estás comentando la solución de otra persona. Comparte tu perspectiva de forma constructiva y respetuosa.

Debes iniciar sesión para publicar un comentario.