JavaScript · Syntax · Advanced
Design patterns
Reusable solutions to common structural and behavioural problems. Covers Observer, Strategy, Factory, and Decorator pattern in plain JavaScript.
Quick topic start and explanations before exercises (exercises below):
Factory, Decorator (HOF + pipe), Command with undo/redo
#Pattern table, functional alternatives, when not to, recognition guide
#Exercises:
Observer: EventEmitter class
#Implement an `EventEmitter` class with three methods: `on(event, listener)` — register a listener; `off(event, listener)` — remove a listener; `emit(event, ...args)` — call all listeners for that event with the given args.
class EventEmitter {
constructor() {
this._listeners = {};
}
on(event, listener) {
// register listener
}
off(event, listener) {
// remove listener
}
emit(event, ...args) {
// call all listeners
}
}
const emitter = new EventEmitter();
const greet = name => console.log(`Hello, ${name}!`);
emitter.on('greet', greet);
emitter.emit('greet', 'Alice'); // Hello, Alice!
emitter.emit('greet', 'Bob'); // Hello, Bob!
emitter.off('greet', greet);
emitter.emit('greet', 'Carol'); // (nothing)
Solution
class EventEmitter {
constructor() {
this._listeners = {};
}
on(event, listener) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push(listener);
}
off(event, listener) {
if (!this._listeners[event]) return;
this._listeners[event] = this._listeners[event].filter(l => l !== listener);
}
emit(event, ...args) {
(this._listeners[event] || []).forEach(l => l(...args));
}
}
const emitter = new EventEmitter();
const greet = name => console.log(`Hello, ${name}!`);
emitter.on('greet', greet);
emitter.emit('greet', 'Alice'); // Hello, Alice!
emitter.emit('greet', 'Bob'); // Hello, Bob!
emitter.off('greet', greet);
emitter.emit('greet', 'Carol'); // (nothing)
Observer: once() — fire only once
#Add an `once(event, listener)` method to `EventEmitter`. It should register a listener that is automatically removed after it fires once.
class EventEmitter {
constructor() { this._listeners = {}; }
on(event, fn) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push(fn);
}
off(event, fn) {
if (!this._listeners[event]) return;
this._listeners[event] = this._listeners[event].filter(l => l !== fn);
}
emit(event, ...args) {
(this._listeners[event] || []).forEach(l => l(...args));
}
once(event, fn) {
// fires fn once, then auto-removes
}
}
const ee = new EventEmitter();
ee.once('connect', () => console.log('connected!'));
ee.emit('connect'); // connected!
ee.emit('connect'); // (nothing)
Solution
class EventEmitter {
constructor() { this._listeners = {}; }
on(event, fn) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push(fn);
}
off(event, fn) {
if (!this._listeners[event]) return;
this._listeners[event] = this._listeners[event].filter(l => l !== fn);
}
emit(event, ...args) {
(this._listeners[event] || []).forEach(l => l(...args));
}
once(event, fn) {
const wrapper = (...args) => {
fn(...args);
this.off(event, wrapper);
};
this.on(event, wrapper);
}
}
const ee = new EventEmitter();
ee.once('connect', () => console.log('connected!'));
ee.emit('connect'); // connected!
ee.emit('connect'); // (nothing)
Strategy: swap sorting algorithms
#Create a `Sorter` class with a `sort(arr)` method. The sorting algorithm is injected via the constructor as a strategy function. Support at least two strategies: bubble sort and built-in sort. Demonstrate swapping strategies at runtime.
class Sorter {
constructor(strategy) {
this.strategy = strategy;
}
sort(arr) {
return this.strategy([...arr]);
}
}
const bubbleSort = arr => {
// implement bubble sort
};
const nativeSort = arr => arr.sort((a, b) => a - b);
const sorter = new Sorter(bubbleSort);
console.log(sorter.sort([3, 1, 4, 1, 5])); // [1, 1, 3, 4, 5]
sorter.strategy = nativeSort; // swap strategy
console.log(sorter.sort([9, 2, 7])); // [2, 7, 9]
Solution
class Sorter {
constructor(strategy) {
this.strategy = strategy;
}
sort(arr) {
return this.strategy([...arr]);
}
}
const bubbleSort = arr => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
return arr;
};
const nativeSort = arr => arr.sort((a, b) => a - b);
const sorter = new Sorter(bubbleSort);
console.log(sorter.sort([3, 1, 4, 1, 5])); // [1, 1, 3, 4, 5]
sorter.strategy = nativeSort;
console.log(sorter.sort([9, 2, 7])); // [2, 7, 9]
Strategy: payment methods
#Create a `Checkout` class with a `pay(amount)` method. Three payment strategies: `creditCard`, `paypal`, and `crypto` — each is a function that takes an amount and logs a payment message. The strategy is set via `checkout.setStrategy(fn)`.
const creditCard = amount => console.log(`Charged $${amount} to credit card`);
const paypal = amount => console.log(`Sent $${amount} via PayPal`);
const crypto = amount => console.log(`Transferred $${amount} in BTC`);
class Checkout {
setStrategy(strategy) {
this.strategy = strategy;
}
pay(amount) {
// call this.strategy
}
}
const checkout = new Checkout();
checkout.setStrategy(creditCard);
checkout.pay(50); // Charged $50 to credit card
checkout.setStrategy(paypal);
checkout.pay(30); // Sent $30 via PayPal
Solution
const creditCard = amount => console.log(`Charged $${amount} to credit card`);
const paypal = amount => console.log(`Sent $${amount} via PayPal`);
const crypto = amount => console.log(`Transferred $${amount} in BTC`);
class Checkout {
setStrategy(strategy) {
this.strategy = strategy;
}
pay(amount) {
if (!this.strategy) throw new Error('No payment strategy set');
this.strategy(amount);
}
}
const checkout = new Checkout();
checkout.setStrategy(creditCard);
checkout.pay(50); // Charged $50 to credit card
checkout.setStrategy(paypal);
checkout.pay(30); // Sent $30 via PayPal
checkout.setStrategy(crypto);
checkout.pay(100); // Transferred $100 in BTC
Factory: shape creator
#Write a factory function `createShape(type, ...dims)` that creates shape objects. Supported types: `'circle'` (radius), `'rect'` (width, height). Each shape object must have an `area()` method. Throw an error for unknown types.
function createShape(type, ...dims) {
// return shape object based on type
}
const c = createShape('circle', 5);
console.log(c.area().toFixed(2)); // 78.54
const r = createShape('rect', 4, 3);
console.log(r.area()); // 12
createShape('triangle', 3, 4, 5); // Error: Unknown shape: triangle
Solution
function createShape(type, ...dims) {
switch (type) {
case 'circle': {
const [r] = dims;
return { type: 'circle', area: () => Math.PI * r * r };
}
case 'rect': {
const [w, h] = dims;
return { type: 'rect', area: () => w * h };
}
default:
throw new Error(`Unknown shape: ${type}`);
}
}
const c = createShape('circle', 5);
console.log(c.area().toFixed(2)); // 78.54
const r = createShape('rect', 4, 3);
console.log(r.area()); // 12
Decorator: add logging to any function
#Write a `withLogging(fn)` decorator that wraps any function. Before calling the original, log `'Calling <fn.name> with <args>'`. After it returns, log `'<fn.name> returned <result>'`. Return a new function with the same signature.
function withLogging(fn) {
return function(...args) {
// log before call
// call fn
// log after
// return result
};
}
function add(a, b) { return a + b; }
const loggedAdd = withLogging(add);
loggedAdd(2, 3);
// Calling add with 2,3
// add returned 5
Solution
function withLogging(fn) {
return function(...args) {
console.log(`Calling ${fn.name} with ${args}`);
const result = fn(...args);
console.log(`${fn.name} returned ${result}`);
return result;
};
}
function add(a, b) { return a + b; }
const loggedAdd = withLogging(add);
loggedAdd(2, 3);
// Calling add with 2,3
// add returned 5
Decorator: memoize
#Write a `memoize(fn)` decorator that caches results by arguments. On repeated calls with the same args, return the cached value without re-running `fn`. Use a `Map` for the cache. Test with a slow `factorial` that logs when it actually runs.
function memoize(fn) {
const cache = new Map();
return function(...args) {
// check cache, compute if miss, store and return
};
}
function factorial(n) {
console.log(`Computing factorial(${n})`);
return n <= 1 ? 1 : n * factorial(n - 1);
}
const memoFactorial = memoize(factorial);
console.log(memoFactorial(5)); // logs Computing 5..1, returns 120
console.log(memoFactorial(5)); // no 'Computing' logs — cached
console.log(memoFactorial(3)); // logs Computing 3..1
Solution
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}
function factorial(n) {
console.log(`Computing factorial(${n})`);
return n <= 1 ? 1 : n * factorial(n - 1);
}
const memoFactorial = memoize(factorial);
console.log(memoFactorial(5));
console.log(memoFactorial(5)); // cached, no Computing logs
Singleton: module-level instance
#Implement a `Logger` singleton using the ES module pattern. The module exports a single `logger` instance. All importers should share the same instance — logged messages accumulate across calls. Show that calling `logger.log()` from two different 'files' adds to the same log.
// logger.js
class Logger {
constructor() {
this.messages = [];
}
log(msg) {
this.messages.push(msg);
console.log(`[LOG] ${msg}`);
}
getAll() { return this.messages; }
}
export const logger = new Logger(); // single instance
// fileA.js
import { logger } from './logger.js';
logger.log('Event from A');
// fileB.js
import { logger } from './logger.js';
logger.log('Event from B');
console.log(logger.getAll()); // ['Event from A', 'Event from B']
Solution
// logger.js
class Logger {
constructor() { this.messages = []; }
log(msg) { this.messages.push(msg); console.log(`[LOG] ${msg}`); }
getAll() { return this.messages; }
}
export const logger = new Logger();
// In Node.js or bundled code, both imports return the same object.
// Simulating two files in one script:
const logger1 = { messages: [], log(m) { this.messages.push(m); }, getAll() { return this.messages; } };
const logger2 = logger1; // same reference
logger1.log('Event from A');
logger2.log('Event from B');
console.log(logger1.getAll()); // ['Event from A', 'Event from B']
Functional composition as decoration
#Write a `compose(...fns)` function that returns a new function applying the given functions right-to-left. Then use it to build a text pipeline: `trim` -> `lowercase` -> `exclaim` (add `!`). Composing these three produces a function that applies all three in sequence.
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const trim = s => s.trim();
const lowercase = s => s.toLowerCase();
const exclaim = s => s + '!';
const process = compose(exclaim, lowercase, trim);
console.log(process(' Hello World ')); // hello world!
Solution
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const trim = s => s.trim();
const lowercase = s => s.toLowerCase();
const exclaim = s => s + '!';
const process = compose(exclaim, lowercase, trim);
console.log(process(' Hello World ')); // hello world!
// Also try pipe (left-to-right):
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const process2 = pipe(trim, lowercase, exclaim);
console.log(process2(' Hello World ')); // hello world!
Observer: typed event bus with payload
#Create an `EventBus` where events carry typed payloads. `subscribe(type, handler)` — register a handler; `publish(type, payload)` — call all handlers for that type with the payload; `unsubscribe(type, handler)` — remove a handler. Demonstrate with a 'user:login' event carrying `{ userId, name }`.
class EventBus {
constructor() { this._handlers = {}; }
subscribe(type, handler) {
// register handler
}
unsubscribe(type, handler) {
// remove handler
}
publish(type, payload) {
// call all handlers
}
}
const bus = new EventBus();
const onLogin = ({ userId, name }) => console.log(`User ${name} (${userId}) logged in`);
bus.subscribe('user:login', onLogin);
bus.publish('user:login', { userId: 42, name: 'Alice' });
// User Alice (42) logged in
bus.unsubscribe('user:login', onLogin);
bus.publish('user:login', { userId: 99, name: 'Bob' }); // (nothing)
Solution
class EventBus {
constructor() { this._handlers = {}; }
subscribe(type, handler) {
if (!this._handlers[type]) this._handlers[type] = [];
this._handlers[type].push(handler);
}
unsubscribe(type, handler) {
if (!this._handlers[type]) return;
this._handlers[type] = this._handlers[type].filter(h => h !== handler);
}
publish(type, payload) {
(this._handlers[type] || []).forEach(h => h(payload));
}
}
const bus = new EventBus();
const onLogin = ({ userId, name }) => console.log(`User ${name} (${userId}) logged in`);
bus.subscribe('user:login', onLogin);
bus.publish('user:login', { userId: 42, name: 'Alice' });
bus.unsubscribe('user:login', onLogin);
bus.publish('user:login', { userId: 99, name: 'Bob' }); // (nothing)