JS Built-ins
DesignPatternsintermediate

Decorator β€” Call tracking

πŸ“– Usage Example
function callTracker(fn) {
  let count = 0;
  function tracked(...args) { count++; return fn.apply(this, args); }
  tracked.callCount = () => count;
  return tracked;
}

Track how many times a function has been called by wrapping it in a counter.

Decorator Pattern β€” Tracking Function Calls

A decorator can track how many times a function is called.

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

  • Call the original function
  • Return the result
  • Internally count how many times it was called

The decorator should add a callCount property to the wrapper.

Example:

const fn = (x) => x * 2
const t = tracked(fn)
t(5)
t(3)
t.callCount // 2
πŸ’‘ Hints (4)
  • β€’ Create a wrapper function
  • β€’ Add callCount property to wrapper
  • β€’ Increment callCount on each call
  • β€’ Return the result from the original function