Count how often a function was called
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; // 0const boom = withCallCount(() => { throw new Error("x"); });
try { boom(); } catch {}
try { boom(); } catch {}
boom.callCount; // 2 — counted even though every call threwCounting happens before the call, so exceptions do not escape the tally.
What it has to do
callCountis0before 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()setscallCountback to0.- Two wrappers around the same function keep separate counts.
Notes
- Functions in JS are objects, so hang
callCountandresetdirectly on the wrapper — no outer object required. - Use a named function declaration (
function wrapper(...) {}) so the body can referencewrapperto updatewrapper.callCountby name.
Stuck? The javascript course covers everything this challenge needs.
- 1.starts at zero
- 2.counts calls and returns the result
- 3.counts a call that throws
- 4.reset clears the tally
- 5.two wrappers count separately
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.