Skip to content

Percentage discount with a cap

A discount function takes a percent and a cap. Tests for 20% off and for the cap both pass. But a percent over 100 (two coupons used together) makes the price negative: applyDiscount(5000, 150, 10000) is -2500. A negative percent makes the price go up.

src/pricing.ts
export function applyDiscount(priceCents: number, percent: number, capCents: number): number {
const discount = Math.min(Math.floor((priceCents * percent) / 100), capCents);
return priceCents - discount;
}

See how Lean finds and fixes it.

Last updated: