Polski

Discount strategy

Interchangeable discount algorithms in a checkout: percentage, threshold and "best of", swapped at runtime.

medium · python · typescript · 20 XP

Checkout computes the order total, while the discount comes from a strategy passed in from outside. Marketing can add new promotions without touching the checkout code.

Task

  • PercentageDiscount(percent) – lowers the price by a percentage; a percentage outside 0–100 → exception (ValueError in Python, Error('Percent must be between 0 and 100') in TypeScript).
  • ThresholdDiscount(threshold, amount) – from threshold on, subtracts amount, never below zero.
  • BestDiscount(...strategies) – applies whichever strategy gives the lowest price (a strategy composed of strategies).
  • Checkout.total(items) – sum of price × quantity, then the strategy, rounded to cents; set_strategy / setStrategy swaps the strategy at runtime.
CartStrategyResult
2 × 100 + 1 × 5010%225.00
2 × 100 + 1 × 5030 off from 200220.00
9.9933%6.69

Topics: Strategy