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);

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.

Further reading

Problem with a question

Design Patterns · Middle · question 1

Test yourself

Take the Design Patterns · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz