Implement a TypeScript function that applies one coupon to a cart at checkout. Put coupon.ts at the submission root and export:
export function applyCoupon(cart: Cart, coupon: Coupon, context: CouponContext): CouponResult;
Do not use external packages, network access, or the file system.
Input and output
interface Cart { subtotal: number } // Product subtotal in KRW
interface Coupon {
id: string;
type: 'fixed' | 'percent';
value: number; // KRW for fixed; percentage for percent
minSubtotal: number; // Minimum order amount in KRW
expiresAt: string; // ISO 8601 expiration timestamp
}
interface CouponContext { now: string; usedCouponIds: string[] } // ISO 8601 current timestamp
interface CouponResult {
accepted: boolean;
discount: number;
total: number;
reason: 'ok' | 'invalid' | 'minimum' | 'expired' | 'used';
}
Rules
- Validation (
invalid) — returnreason: 'invalid'if any condition fails:cart.subtotalis a finite nonnegative integer in KRW.coupon.idis a string.coupon.typeis'fixed'or'percent'; any other value is invalid.- For a fixed coupon,
coupon.valueis a finite nonnegative integer in KRW. - For a percent coupon,
coupon.valueis a finite number from 0 to 100 inclusive; fractions are allowed. coupon.minSubtotalis a finite nonnegative integer in KRW.coupon.expiresAtandcontext.noware date strings. A date for whichDate.parsereturnsNaNis invalid.context.usedCouponIdsis an array of strings.
- Minimum (
minimum) — reject ifcart.subtotal < coupon.minSubtotal. Equality passes. - Expiry (
expired) — reject ifDate.parse(coupon.expiresAt) <= Date.parse(context.now). Equality means the coupon has expired. - Reuse (
used) — reject ifcontext.usedCouponIdscontainscoupon.id. - Apply (
ok) — otherwise apply the coupon:- Fixed discount:
coupon.value. - Percentage discount:
Math.floor(cart.subtotal * coupon.value / 100), rounding down to whole KRW. - Cap the discount at
cart.subtotal; the total cannot be negative. - Return
{ accepted: true, discount, total: cart.subtotal - discount, reason: 'ok' }.
- Fixed discount:
Decision order and rejected results
- When multiple conditions apply, return only the first reason in this order:
invalid → minimum → expired → used. - Rejected results use
accepted: falseanddiscount: 0. - On rejection,
totalis the originalcart.subtotal. If that subtotal itself is invalid under rule 1, usetotal: 0. - Do not mutate
cart,coupon,context, or theusedCouponIdsarray. - The same input must always produce the same result. Use only
context.nowfor current time, neverDate.now().
Scoring
Seven automatic groups earn 1,000 basis points each: fixed discount, percentage discount, minimum, expiry, reuse, cap, and regression. A group passes only if all of its cases pass. Submitted code runs only in a network-disabled Docker sandbox. Build failure, timeout, or memory exhaustion gives zero automatic points. A human reviewer scores structure, practicality, and depth at 1,000 basis points each. The score is provisional until review.