export type CartItem = { sku: string; unitPriceCents: number; quantity: number };export type Coupon = | { kind: "percent"; percent: number } | { kind: "fixed"; amountCents: number; minSubtotalCents?: number };export type CartTotal = { subtotalCents: number; discountCents: number; totalCents: number };export type CartErrorKind = "invalid_item" | "unknown_coupon" | "coupon_not_applicable";export class CartError extends Error { readonly index?: number; readonly code?: string; constructor( public readonly kind: CartErrorKind, detail: { index?: number; code?: string } = {}, ) { super(kind); Object.assign(this, detail); }}const isCount = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v) && v >= 0;/** Throws CartError. */export function cartTotal( items: CartItem[], couponCode: string | undefined, coupons: Record<string, Coupon>,): CartTotal { let subtotalCents = 0; items.forEach((item, index) => { if (!isCount(item.unitPriceCents) || !isCount(item.quantity)) { throw new CartError("invalid_item", { index }); } subtotalCents += item.unitPriceCents * item.quantity; }); let discountCents = 0; if (couponCode !== undefined && couponCode !== null && couponCode.trim() !== "") { const key = couponCode.trim().toLowerCase(); if (!Object.hasOwn(coupons, key)) throw new CartError("unknown_coupon", { code: couponCode }); const coupon = coupons[key]; if (coupon.kind === "percent") { discountCents = Math.floor((subtotalCents * coupon.percent) / 100); } else { const min = coupon.minSubtotalCents; if (min !== undefined && min !== null && subtotalCents < min) { throw new CartError("coupon_not_applicable", { code: couponCode }); } discountCents = Math.min(coupon.amountCents, subtotalCents); } } return { subtotalCents, discountCents, totalCents: subtotalCents - discountCents };}