JS Built-ins
DesignPatternsbeginner

Decorator β€” Timed function

πŸ“– Usage Example
function timed(fn) {
  return function(...args) {
    const start = Date.now();
    const result = fn.apply(this, args);
    console.log(Date.now() - start, 'ms');
    return result;
  };
}

A timing decorator measures how long a function takes to execute.

Decorator Pattern β€” Timing Execution

A decorator can measure and track function execution time.

Challenge: Implement a timed(fn) decorator that wraps a function. The wrapper should:

  • Call the original function
  • Return the result unchanged

(The timing behavior is internal; we're testing that the result is correct)

Example:

const slow = (x) => x * 2
const timedSlow = timed(slow)
timedSlow(5) // returns 10
πŸ’‘ Hints (3)
  • β€’ Capture the start time
  • β€’ Call the original function
  • β€’ Return the result from the original function