peppa/bench/tasks/03-bugfix/checks/buggy-cart.mjs.txt
2026-11-17 02:09:17 +05:00

38 lines
1.5 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// BENCH-HIDDEN — исходный расчёт с ошибкой (для проверки, что тест её ловит).
// Расчёт заказа: сумма, скидка по промокоду, доставка, итог.
import { findItem } from "./catalog.mjs";
export const DELIVERY_FEE = 1000;
export const FREE_DELIVERY_FROM = 5000;
export const PROMOS = { SPRING10: 0.1, FRIEND15: 0.15 };
export class CartError extends Error {}
function lines(items) {
return (items ?? []).map(({ sku, qty }) => {
const item = findItem(sku);
if (!item) throw new CartError(`Нет такого товара: ${sku}`);
const n = Number(qty);
if (!Number.isInteger(n) || n < 1 || n > 99) throw new CartError("Количество — от 1 до 99");
return { ...item, qty: n, sum: item.price * n };
});
}
function discountFor(subtotal, promo) {
const code = String(promo ?? "").trim().toUpperCase();
if (!code) return 0;
const rate = PROMOS[code];
if (rate === undefined) throw new CartError("Такого промокода нет");
return Math.round(subtotal * rate);
}
export function quote(items, promo) {
const rows = lines(items);
if (rows.length === 0) throw new CartError("Корзина пуста");
const subtotal = rows.reduce((s, r) => s + r.sum, 0);
const discount = discountFor(subtotal, promo);
const payable = subtotal - discount;
const delivery = payable > FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;
return { lines: rows, subtotal, discount, delivery, total: payable + delivery };
}