Design Patterns · Middle · Question 1 of 75
Which pattern was applied in this refactoring?
// before
function price(type, sum) {
if (type === "vip") return sum * 0.8;
if (type === "sale") return sum * 0.9;
return sum;
}
// after
const discounts = { vip: s => s * 0.8, sale: s => s * 0.9, regular: s => s };
const price = (type, sum) => discounts[type](sum);- ✓Correct answer: Strategy: the algorithms were moved into interchangeable functions
- 2Singleton: all discounts are stored in one shared global object
- 3Template Method: the base calculation is overridden in subclasses
Explanation
Each discount is a separate strategy, and a new one is added without editing the price function (also an example of OCP). In JS, a strategy is often just an object of functions instead of a class hierarchy.