Strategy
Strategy is swapping an algorithm behind a shared interface. In JavaScript that interface is usually a function you pass in, not a class hierarchy.
Detailed Explanation
You have a sort, a payment method, a compression choice, a pricing rule. The surrounding code should not if (type === "visa") in five places. It should call pay(amount) where pay is the strategy you selected once.
Because functions are values, the pattern is a parameter:
function checkout(cart, pay) {
return pay(cart.total);
}
checkout(cart, payWithCard);
checkout(cart, payWithPoints);
A class strategy (class Card { pay() {} }) is useful when the algorithm has state (a retry count, a client). A map of strategies (const methods = { card, points }) is a registry. methods[name] is the factory plus strategy combo.
array.sort(comparator) is strategy. array.map(fn) is strategy. Intl.Collator is a strategy object. You already use this.
The invariant is the contract: same arguments, same meaning of the return, same error type. A strategy that sometimes returns a promise and sometimes a number will break callers. Document sync vs async and keep it stable.
What it costs you: too many tiny functions, and a registry keyed by strings that fail at runtime. Prefer passing the function you already have over a global strategies["card"] unless the choice arrives as data (a user setting).
Reach for strategy when several algorithms are interchangeable at a call site. Reach for inheritance when the types truly are variants with extra fields. Reach for a switch when there are two cases and they will not grow.
Strategies should be cheap to construct. If creating a strategy opens a socket, the registry is a resource leak. Create the heavy client once and pass it into the strategy function: (client) => (amount) => client.charge(amount).
Feature flags that pick a strategy at runtime belong at the edge (the request handler), not sprinkled inside the algorithm. That keeps tests able to pass a strategy directly without mocking the flag service.
Code Examples
const byPrice = (a, b) => a.price - b.price;
const byName = (a, b) => a.name.localeCompare(b.name);
const items = [
{ name: "desk", price: 80 },
{ name: "book", price: 10 },
];
console.log([...items].sort(byPrice).map((i) => i.name)); // => [ 'book', 'desk' ]
console.log([...items].sort(byName).map((i) => i.name)); // => [ 'book', 'desk' ]function format(value, strategy) {
return strategy(value);
}
const usd = (n) => `$${n.toFixed(2)}`;
const cents = (n) => `${Math.round(n * 100)}¢`;
console.log(format(1.5, usd)); // => $1.50
console.log(format(1.5, cents)); // => 150¢const ship = {
ground: (kg) => kg * 2,
air: (kg) => kg * 5,
};
function quote(kg, method) {
const calc = ship[method];
if (!calc) throw new Error(`unknown ${method}`);
return calc(kg);
}
console.log(quote(3, "air")); // => 15Common Gotchas
Strategies must share a contract
mixing sync and async, or returning different shapes, pushes `if` back into the caller.
String-keyed registries fail late
validate `method` at the boundary.
A one-method class is often a function
do not add a hierarchy for a single `pay()`.
Closures let a strategy carry config
`const usd = (fx) => (n) => ...` is still strategy.