Order Processor Refactoring with Guard Clauses and Helper Functions
Refactor the legacy Código con Criterio order processor with Nexo using early returns, descriptive constants, and single-responsibility helper functions while preserving its exact behavior.
Nexo found a legacy module in the Código con Criterio order processor. The current code works properly and passes all business rules, but suffers from deep nesting (cascading if/else blocks), cryptic variable names (a, b, c, d), magic numbers, and duplicated response objects.
Your mission is to refactor the code while preserving its exact functional behavior across all scenarios.
solve(input) Input
productos: array of 0 to 50 objects with id (unique integer from 1 to 10000), precio (integer from 0 to 100000 cents), stock (integer from 0 to 100), and activo (boolean).
pedido: object with productoId (integer from 1 to 10000, may not exist), cantidad (integer from 1 to 100), and tipoCliente ("NORMAL" or "PREMIUM").
dineroDisponible: integer from 0 to 10000000 cents.
Business Rules to Preserve Intact
Strict validation order:
If the product does not exist in productos, return status "PRODUCTO_NO_ENCONTRADO".
If !producto.activo, return status "PRODUCTO_INACTIVO".
If pedido.cantidad > producto.stock, return status "STOCK_INSUFICIENTE".
On any of these three rejections prior to monetary calculation, subtotal, descuento, and total are 0, and saldoRestante equals dineroDisponible.
Monetary calculation and balance check:
subtotal = producto.precio * pedido.cantidad.
descuento = Math.floor(subtotal * 10 / 100) for "PREMIUM" customers, or 0 for "NORMAL".
total = subtotal - descuento.
If dineroDisponible < total, return status "DINERO_INSUFICIENTE" while keeping the computed subtotal, descuento, and total, and saldoRestante = dineroDisponible.
If dineroDisponible >= total, return status "APROBADO" and saldoRestante = dineroDisponible - total.
Design Requirements for Your Refactoring
Although automated input/output tests verify functional equivalence, structure your solution following these practices:
Define the constant const DESCUENTO_PREMIUM = 10;.
Extract four single-responsibility helper functions:
buscarProducto(productos, productoId): returns the matching product or null.