AniUI Academy

Count how often a function was called

easyFunctions & Closures+150 XPPractice

You suspect a render callback is firing far more often than it should. Rather than littering the function with counters, wrap it: the wrapper does the counting and exposes the tally, and the wrapped function is unchanged.

Implement withCallCount(fn). It returns a wrapper that forwards all of its arguments to fn and returns fn's return value. The wrapper also carries two extra properties: callCount, a number that starts at 0 and rises by one on every call, and reset(), which sets callCount back to 0. Count the call before invoking fn, so a call where fn throws is still counted. Each wrapper keeps its own tally, even when two wrappers wrap the same function.

Arguments

fnFunction
The function to wrap and tally.

Returns

Function & { callCount: number; reset(): void } — A wrapper that behaves like fn and exposes callCount plus a reset() method.

Examples

const add = withCallCount((a, b) => a + b);

add(1, 2);           // 3
add(3, 4);           // 7
add.callCount;       // 2
add.reset();
add.callCount;       // 0
const boom = withCallCount(() => { throw new Error("x"); });

try { boom(); } catch {}
try { boom(); } catch {}
boom.callCount; // 2 — counted even though every call threw

Counting happens before the call, so exceptions do not escape the tally.

What it has to do

  • callCount is 0 before the wrapper is called and increases by one per call.
  • The wrapper forwards its arguments and returns fn's return value.
  • A call that throws is still counted, because counting happens before the call.
  • reset() sets callCount back to 0.
  • Two wrappers around the same function keep separate counts.

Notes

  • Functions in JS are objects, so hang callCount and reset directly on the wrapper — no outer object required.
  • Use a named function declaration (function wrapper(...) {}) so the body can reference wrapper to update wrapper.callCount by name.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.