JS Built-ins
DesignPatternsbeginner

Decorator β€” Logged function

πŸ“– Usage Example
function logged(fn) {
  return function(...args) {
    console.log('calling', fn.name);
    return fn.apply(this, args);
  };
}
const safeAdd = logged(add);

The decorator pattern wraps a function to add behavior without modifying the original.

Decorator Pattern β€” Adding Behavior

A decorator wraps a function to add behavior without modifying the original. In JavaScript, this is a higher-order function.

Challenge: Implement a logged(fn) decorator that wraps a function. The wrapper should call the original function and return its result.

Example:

const add = (a, b) => a + b
const loggedAdd = logged(add)
loggedAdd(2, 3) // calls add, returns 5
πŸ’‘ Hints (3)
  • β€’ Return a function from logged
  • β€’ Pass all arguments to the original function
  • β€’ Return the result from the original function