Patterns & principles · 5 of 10 · 13 min read
The Strategy pattern
Interchangeable algorithms chosen at runtime — which in JavaScript is usually an object of functions replacing a growing switch.
- Design patterns
Strategy means: several interchangeable ways of doing one job, selected when the program runs. Classic implementations use a class per algorithm and an interface. JavaScript has first-class functions, so a strategy is usually just a function, and the set of them is an object.
The problem it solves
function getPrice(order, customer) {
switch (customer.type) {
case 'regular':
return order.total;
case 'member':
return order.total * 0.9;
case 'vip':
return order.total * 0.8;
case 'staff':
return order.total * 0.5;
default:
throw new RangeError(`unknown customer type: ${customer.type}`);
}
}
Nothing is wrong with it at four cases. The problem is the direction it grows: every new customer
type reopens this function, every change risks the cases around it, and testing one rule means
calling getPrice with a whole order.
The lookup object
const pricing = {
regular: (total) => total,
member: (total) => total * 0.9,
vip: (total) => total * 0.8,
staff: (total) => total * 0.5,
};
function getPrice(order, customer) {
const strategy = pricing[customer.type] ?? pricing.regular; // a named default
return strategy(order.total);
}
console.log(getPrice({ total: 100 }, { type: 'vip' })); // 80
console.log(getPrice({ total: 100 }, { type: 'unknown' })); // 100 — fell back
Adding student: (total) => total * 0.7 is one line, in one place, and touches none of the
existing rules. Each rule is a pure function you can test on its own:
console.log(pricing.vip(200)); // 160 — no order, no customer, no mocking
switch |
Lookup object | |
|---|---|---|
| Adding a case | edits the function | adds a key |
| Testing one rule | through the whole function | call it directly |
| Rules can come from elsewhere | no | yes — config, a plugin, a database |
| Default | the default branch |
?? fallback |
| Reads well at 3 cases | yes | yes |
| Reads well at 30 | no | yes |
Keep the lookup safe
A plain object inherits from Object.prototype, so a lookup keyed by user input can find things
you did not put there:
const strategies = { a: () => 'A' };
console.log(typeof strategies['toString']); // "function" — inherited, not yours
Two fixes, either is fine:
// 1. A prototype-less object — nothing to inherit.
const safe = Object.assign(Object.create(null), { a: () => 'A' });
console.log(safe['toString']); // undefined
// 2. A Map — keys are only what you put in it.
const byType = new Map([['a', () => 'A']]);
console.log(byType.has('toString'), byType.get('a')()); // false "A"
A Map also lets strategies be registered at runtime, which is what turns this into a plugin
point:
const validators = new Map();
export const register = (name, fn) => validators.set(name, fn);
export const validate = (name, value) =>
(validators.get(name) ?? (() => true))(value);
register('email', (v) => v.includes('@'));
console.log(validate('email', 'a@b.c'), validate('email', 'nope')); // true false
Strategies with state or options
When a strategy needs configuring, make it a factory — a function that returns the strategy:
const shipping = {
flat: (rate) => (weight) => rate,
perKilo: (rate) => (weight) => weight * rate,
tiered: (tiers) => (weight) =>
tiers.find(({ upTo }) => weight <= upTo)?.price ?? tiers.at(-1).price,
};
const calculate = shipping.tiered([
{ upTo: 1, price: 5 },
{ upTo: 5, price: 12 },
{ upTo: Infinity, price: 30 },
]);
console.log(calculate(0.5), calculate(3), calculate(50)); // 5 12 30
And when a strategy needs several operations rather than one, it becomes an object — which is the original Gang of Four shape, minus the interface declaration:
const formats = {
json: {
extension: '.json',
serialise: (data) => JSON.stringify(data, null, 2),
},
csv: {
extension: '.csv',
serialise: (data) =>
[Object.keys(data[0]).join(','), ...data.map((r) => Object.values(r).join(','))].join('\n'),
},
};
function exportTo(format, data) {
const { extension, serialise } = formats[format];
return { filename: `export${extension}`, body: serialise(data) };
}
console.log(exportTo('csv', [{ a: 1, b: 2 }]).body); // "a,b\n1,2"
JavaScript has no interface to enforce that every strategy has both keys, so the contract is a
convention. In TypeScript it is a type; in plain JS, a test that iterates the registry is the
cheapest enforcement:
for (const [name, strategy] of Object.entries(formats)) {
console.log(name, typeof strategy.serialise === 'function'); // json true / csv true
}
Where it already exists
The callback-taking methods you use every day are Strategy: the method owns the algorithm’s structure, you supply the varying part.
const people = [{ age: 30 }, { age: 20 }];
console.log([...people].sort((a, b) => a.age - b.age)[0].age); // 20 — comparison strategy
console.log(people.map((p) => p.age)); // transformation strategy
console.log(people.filter((p) => p.age > 25).length); // predicate strategy
sort does not know how you want things ordered, and never needs to. That is the pattern, built
into the standard library.
Open/Closed, concretely
This is the cleanest example of the O in SOLID: the pricing module is open for extension — anyone can add a strategy — and closed for modification — doing so edits nothing that already works.
// pricing.js
const rules = new Map([['regular', (t) => t]]);
export const addRule = (name, fn) => rules.set(name, fn);
export const price = (type, total) => (rules.get(type) ?? rules.get('regular'))(total);
// promotions.js — a new file, zero changes to pricing.js
addRule('black-friday', (total) => total * 0.6);
console.log(price('black-friday', 100)); // 60
Common mistakes
A lookup keyed by unvalidated input with no fallback
Mistake. strategies[req.body.type](value).
Why it fails. An unknown type gives undefined, and calling it throws TypeError: … is not a function — a confusing error far from the bad input, or worse, an inherited method that is
callable.
What to do instead. Object.create(null) or a Map, plus an explicit default or a clear
throw: const fn = rules.get(type); if (!fn) throw new RangeError(...).
Strategies that need different arguments
Mistake. card(amount, cvv) next to transfer(amount, iban) in the same registry.
Why it fails. They are not interchangeable, so the caller needs to know which one it picked —
and the switch comes back, disguised.
What to do instead. One argument object with the shape every strategy accepts, or accept that
these are different operations and not strategies at all.
Reaching for it at two cases
Mistake. A registry, a factory and a plugin point for if (isAdmin) … else ….
Why it fails. Indirection with nothing on the other end: the reader now has two files to open
to learn what an if would have told them.
What to do instead. Write the if. Introduce the pattern when the third or fourth case
arrives, which is the point where the switch starts to hurt.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What does the Strategy pattern let you do?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.