Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.7 KiB · at 9ba9e6b

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: unitPriceCents and quantity must each be a non-negative integer of JavaScript type number (numeric strings, null, NaN and 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 } with percent from 0 to 100, or { kind: "fixed", amountCents, minSubtotalCents } where minSubtotalCents is 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:

  • subtotalCents is the sum of unitPriceCents * quantity.
  • A percent coupon gives discountCents = floor(subtotalCents * percent / 100).
  • A fixed coupon with a minSubtotalCents larger than the subtotal fails with { kind: "coupon_not_applicable", code } (code as passed in). Otherwise it gives discountCents = amountCents, capped at the subtotal so the total is never negative.
  • With no coupon, discountCents is 0. totalCents = subtotalCents - discountCents.

Return { subtotalCents, discountCents, totalCents }. Do not modify the inputs.