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.
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