{"id":"6b0857af5a2625e44ecaad0d","slug":"discount-strategy","title":"Discount strategy","summary":"Interchangeable discount algorithms in a checkout: percentage, threshold and \"best of\", swapped at runtime.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"medium","topics":["strategy"],"techs":["python","typescript"],"tags":["strategy","e-commerce","behavioral"],"languages":[{"lang":"python","runner":"browser","starter":"from abc import ABC, abstractmethod\n\n\nclass DiscountStrategy(ABC):\n    @abstractmethod\n    def apply(self, subtotal: float) -> float:\n        \"\"\"Returns the price after the discount.\"\"\"\n\n\nclass NoDiscount(DiscountStrategy):\n    def apply(self, subtotal: float) -> float:\n        return subtotal\n\n\n# TODO: PercentageDiscount(percent)        – percent must be 0–100, otherwise ValueError\n# TODO: ThresholdDiscount(threshold, amount) – minus amount when subtotal >= threshold, never below 0\n# TODO: BestDiscount(*strategies)            – the lowest price of all given strategies\n\n\nclass Checkout:\n    def __init__(self, strategy: DiscountStrategy):\n        self.strategy = strategy\n\n    def set_strategy(self, strategy: DiscountStrategy) -> None:\n        # TODO\n        pass\n\n    def total(self, items: list[tuple[float, int]]) -> float:\n        # TODO: subtotal = sum of price × quantity, apply the strategy, round to cents\n        raise NotImplementedError\n","testCount":8,"tests":"ITEMS = [(100.0, 2), (50.0, 1)]  # subtotal 250.00\n\n\ndef test_no_discount():\n    got = Checkout(NoDiscount()).total(ITEMS)\n    assert got == 250.0, f\"expected 250.0, got {got}\"\n\n\ndef test_percentage_discount():\n    got = Checkout(PercentageDiscount(10)).total(ITEMS)\n    assert got == 225.0, f\"expected 225.0, got {got}\"\n\n\ndef test_percentage_must_be_between_0_and_100():\n    with raises(ValueError):\n        PercentageDiscount(120)\n\n\ndef test_threshold_discount_applies_from_the_threshold():\n    got = Checkout(ThresholdDiscount(200, 30)).total(ITEMS)\n    assert got == 220.0, f\"expected 220.0, got {got}\"\n    got = Checkout(ThresholdDiscount(300, 30)).total(ITEMS)\n    assert got == 250.0, f\"below the threshold expected 250.0, got {got}\"\n\n\ndef test_threshold_discount_never_goes_below_zero():\n    got = Checkout(ThresholdDiscount(10, 999)).total([(5.0, 2)])\n    assert got == 0.0, f\"expected 0.0, got {got}\"\n\n\ndef test_best_discount_picks_the_lowest_price():\n    best = BestDiscount(PercentageDiscount(10), ThresholdDiscount(200, 30))\n    got = Checkout(best).total(ITEMS)\n    assert got == 220.0, f\"expected 220.0, got {got}\"\n\n\ndef test_strategy_can_be_swapped_at_runtime():\n    checkout = Checkout(NoDiscount())\n    checkout.set_strategy(PercentageDiscount(50))\n    got = checkout.total(ITEMS)\n    assert got == 125.0, f\"expected 125.0, got {got}\"\n\n\ndef test_total_is_rounded_to_cents():\n    got = Checkout(PercentageDiscount(33)).total([(9.99, 1)])\n    assert got == 6.69, f\"expected 6.69, got {got}\"\n"},{"lang":"typescript","runner":"browser","starter":"interface DiscountStrategy {\n  /** Returns the price after the discount. */\n  apply(subtotal: number): number;\n}\n\nclass NoDiscount implements DiscountStrategy {\n  apply(subtotal: number): number {\n    return subtotal;\n  }\n}\n\n// TODO: PercentageDiscount(percent)        – percent must be 0–100, otherwise Error('Percent must be between 0 and 100')\n// TODO: ThresholdDiscount(threshold, amount) – minus amount when subtotal >= threshold, never below 0\n// TODO: BestDiscount(...strategies)          – the lowest price of all given strategies\n\ntype Item = [price: number, quantity: number];\n\nclass Checkout {\n  constructor(private strategy: DiscountStrategy) {}\n\n  setStrategy(strategy: DiscountStrategy): void {\n    // TODO\n  }\n\n  total(items: Item[]): number {\n    // TODO: subtotal = sum of price × quantity, apply the strategy, round to cents\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"const ITEMS = [[100, 2], [50, 1]]; // subtotal 250.00\n\ntest('no discount keeps the subtotal', () => {\n  expect(new Checkout(new NoDiscount()).total(ITEMS)).toBe(250);\n});\n\ntest('percentage discount', () => {\n  expect(new Checkout(new PercentageDiscount(10)).total(ITEMS)).toBe(225);\n});\n\ntest('percentage must be between 0 and 100', () => {\n  expect(() => new PercentageDiscount(120)).toThrow('between 0 and 100');\n});\n\ntest('threshold discount applies from the threshold', () => {\n  expect(new Checkout(new ThresholdDiscount(200, 30)).total(ITEMS)).toBe(220);\n  expect(new Checkout(new ThresholdDiscount(300, 30)).total(ITEMS)).toBe(250);\n});\n\ntest('threshold discount never goes below zero', () => {\n  expect(new Checkout(new ThresholdDiscount(10, 999)).total([[5, 2]])).toBe(0);\n});\n\ntest('best discount picks the lowest price', () => {\n  const best = new BestDiscount(new PercentageDiscount(10), new ThresholdDiscount(200, 30));\n  expect(new Checkout(best).total(ITEMS)).toBe(220);\n});\n\ntest('strategy can be swapped at runtime', () => {\n  const checkout = new Checkout(new NoDiscount());\n  checkout.setStrategy(new PercentageDiscount(50));\n  expect(checkout.total(ITEMS)).toBe(125);\n});\n\ntest('total is rounded to cents', () => {\n  expect(new Checkout(new PercentageDiscount(33)).total([[9.99, 1]])).toBeCloseTo(6.69, 2);\n  expect(new Checkout(new PercentageDiscount(33)).total([[9.99, 1]])).toBe(6.69);\n});\n"}],"questionCount":null,"xp":20,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.764Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Checkout","marks":[{"type":"code"}]},{"type":"text","text":" computes the order total, while the discount comes from a "},{"type":"text","text":"strategy","marks":[{"type":"bold"}]},{"type":"text","text":" passed in from outside. Marketing can add new promotions without touching the checkout code."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"PercentageDiscount(percent)","marks":[{"type":"code"}]},{"type":"text","text":" – lowers the price by a percentage; a percentage outside 0–100 → exception ("},{"type":"text","text":"ValueError","marks":[{"type":"code"}]},{"type":"text","text":" in Python, "},{"type":"text","text":"Error('Percent must be between 0 and 100')","marks":[{"type":"code"}]},{"type":"text","text":" in TypeScript)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ThresholdDiscount(threshold, amount)","marks":[{"type":"code"}]},{"type":"text","text":" – from "},{"type":"text","text":"threshold","marks":[{"type":"code"}]},{"type":"text","text":" on, subtracts "},{"type":"text","text":"amount","marks":[{"type":"code"}]},{"type":"text","text":", never below zero."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"BestDiscount(...strategies)","marks":[{"type":"code"}]},{"type":"text","text":" – applies whichever strategy gives the "},{"type":"text","text":"lowest","marks":[{"type":"bold"}]},{"type":"text","text":" price (a strategy composed of strategies)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Checkout.total(items)","marks":[{"type":"code"}]},{"type":"text","text":" – sum of "},{"type":"text","text":"price × quantity","marks":[{"type":"code"}]},{"type":"text","text":", then the strategy, rounded to cents; "},{"type":"text","text":"set_strategy","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"setStrategy","marks":[{"type":"code"}]},{"type":"text","text":" swaps the strategy at runtime."}]}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Cart"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strategy"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2 × 100 + 1 × 50"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"10%"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"225.00"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2 × 100 + 1 × 50"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"30 off from 200"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"220.00"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"9.99"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"33%"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"6.69"}]}]}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3e80884893657cca1a","slug":"strategy","title":"Strategy: interchangeable algorithms instead of an if-else ladder"},{"id":"6b08bd2f80884893657cc8e8","slug":"bridge","title":"Bridge – two axes of change without a class explosion"}],"topicsInfo":[{"slug":"strategy","title":"Strategy","group":"behavioral","icon":"route"}],"author":{"id":"6b0857a15a2625e44ecaabec","name":"Anna Autorka","avatar":"/api/files/6b0857ec5a2625e44ecab0c6","handle":"anna-autorka","community":true},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-26T16:00:47.766Z","updatedAt":"2026-11-26T16:01:49.526Z"}