Strategy pattern
The strategy pattern defines a family of interchangeable algorithms and lets you choose which one to use at runtime. In JavaScript, since functions are values, it is implemented very naturally by storing functions in an object.
const strategies = {
normal: (price) => price,
member: (price) => price * 0.9, // 10% discount
vip: (price) => price * 0.8, // 20% discount
};
function calculatePrice(price, customerType) {
const strategy = strategies[customerType] || strategies.normal;
return strategy(price);
}
console.log(calculatePrice(100, "vip")); // 80
console.log(calculatePrice(100, "member")); // 90
Why is it useful?
- It eliminates long
if/elseorswitchchains. - Adding a new behavior is as easy as adding a function to the object.
- Each strategy stays isolated and is easy to test separately.
Examples
Strategy to sort in different ways
const sorters = {
asc: (a, b) => a - b,
desc: (a, b) => b - a,
};
const numbers = [3, 1, 2];
console.log([...numbers].sort(sorters.asc));
console.log([...numbers].sort(sorters.desc));