Search⌘ K
AI Features

Solution: Apply Flexible Discounts for Marketing Campaigns

Explore how to implement the Strategy Pattern to manage discount logic dynamically in a Node.js checkout system. Learn to create independent discount strategies—flat, percentage, and loyalty—that can be swapped at runtime without modifying core service logic. This lesson shows how to keep your code flexible and maintainable by avoiding conditional branching and embracing reusable design patterns.

Solution explanation

  • Lines 2–22: We define three discount strategies: FlatDiscountPercentageDiscount, and LoyaltyDiscount.

    • Each strategy encapsulates a distinct pricing rule through a .calculate() method.

    • FlatDiscount applies a fixed numeric deduction.

    • PercentageDiscount multiplies the subtotal to simulate a percentage-based reduction.

    • LoyaltyDiscount simulates a loyalty-tier reduction, representing customer-specific logic.

  • Lines 25–38: ...