Search⌘ K
AI Features

Solution: Track Function Call Count with a Decorator

Understand how to create a decorator that tracks the number of times a function is called, preserving its behavior. This lesson guides you through building a stateful wrapper using closures to log call counts, suitable for both sync and async functions without changing the original code.

Solution explanation

  • Lines 2–4: We define multiply, a pure function that returns the product of two numbers. It stays unmodified—our decorator will add behavior externally.

  • Lines 7–14: We build withCallCount(fn), a stateful decorator:

    • We declare a local variable count initialized to 0.

    • Every time the wrapped function runs, we ...