Write cartTotal(items, couponCode, coupons), which prices a shopping cart. All amounts are integer cents.
Inputs:
items: an array of{ sku, unitPriceCents, quantity }. Items come from an untrusted request:unitPriceCentsandquantitymust each be a non-negative integer of JavaScript type number (numeric strings,null,NaNand fractions are not). The first item that breaks this rule fails with{ kind: "invalid_item", index }. Items are validated before the coupon is looked at.couponCode: optional string. When it is absent, or empty or blank after trimming, no coupon is applied.coupons: the coupon table, keyed by lowercase code. It is trusted configuration. Each coupon is either{ kind: "percent", percent }withpercentfrom 0 to 100, or{ kind: "fixed", amountCents, minSubtotalCents }whereminSubtotalCentsis optional.
The code is looked up after trimming it and converting it to lowercase. Only codes defined in the coupons table itself are valid. A code that is not in the table fails with { kind: "unknown_coupon", code }, where code is the couponCode string exactly as passed in.
Pricing:
subtotalCentsis the sum ofunitPriceCents * quantity.- A percent coupon gives
discountCents = floor(subtotalCents * percent / 100). - A fixed coupon with a
minSubtotalCentslarger than the subtotal fails with{ kind: "coupon_not_applicable", code }(code as passed in). Otherwise it givesdiscountCents = amountCents, capped at the subtotal so the total is never negative. - With no coupon,
discountCentsis 0.totalCents = subtotalCents - discountCents.
Return { subtotalCents, discountCents, totalCents }. Do not modify the inputs.