JS Built-ins
DesignPatternsadvanced

Decorator β€” Stacked decorators

πŸ“– Usage Example
const double = fn => (...a) => fn(...a) * 2;
const addOne = fn => (...a) => fn(...a) + 1;
const square = x => x * x;
const enhanced = addOne(double(square));
enhanced(3); // (9 * 2) + 1 = 19

Stack decorators by nesting them β€” each layer adds behavior on top of the previous.

Decorator Pattern β€” Stacking Multiple Decorators

Multiple decorators can be applied to the same function, each adding different behavior.

Challenge: Create two decorators:

  • double(fn) - multiplies result by 2
  • addTen(fn) - adds 10 to the result

Then compose them: const f = double(addTen(original))

Example:

const original = (x) => x * 2
const f = double(addTen(original))
f(5) // original(5) = 10, addTen(10) = 20, double(20) = 40
πŸ’‘ Hints (4)
  • β€’ Each decorator wraps the previous function
  • β€’ double multiplies the result
  • β€’ addTen adds to the result
  • β€’ Order of application matters