Problem: Track Function Call Count with a Decorator
Problem statement
You’re debugging a utility function that’s being overused in production. You want to track how many times it’s called—without modifying the function itself. We’ll use a decorator to wrap it, maintain an internal counter, and log the count of each invocation. This is a common real-world pattern when adding metrics, telemetry, or usage tracking to shared utilities.
Goal
Create a withCallCount decorator that:
Tracks how many times the wrapped function has been called.
Logs
[COUNT] Function <name> called N times.Works with both synchronous and asynchronous functions.
Preserves the original return value.
Constraints
Do not modify the original function.
Do not use global variables.
The decorator must maintain state internally (use closures).
Preserve the original function’s name in logs.
Sample output
The examples below illustrate what the output should look like:
const countedMultiply = withCallCount(multiply);console.log(countedMultiply(2, 3)); // should log count 1/* Expected output:[COUNT] Function multiply called 1 times6 */console.log(countedMultiply(4, 5)); // should log count 2/* Expected output:[COUNT] Function multiply called 2 times20 */console.log(countedMultiply(6, 7)); // should log count 3/* Expected output:[COUNT] Function multiply called 3 times42 */
Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.
Problem: Track Function Call Count with a Decorator
Problem statement
You’re debugging a utility function that’s being overused in production. You want to track how many times it’s called—without modifying the function itself. We’ll use a decorator to wrap it, maintain an internal counter, and log the count of each invocation. This is a common real-world pattern when adding metrics, telemetry, or usage tracking to shared utilities.
Goal
Create a withCallCount decorator that:
Tracks how many times the wrapped function has been called.
Logs
[COUNT] Function <name> called N times.Works with both synchronous and asynchronous functions.
Preserves the original return value.
Constraints
Do not modify the original function.
Do not use global variables.
The decorator must maintain state internally (use closures).
Preserve the original function’s name in logs.
Sample output
The examples below illustrate what the output should look like:
const countedMultiply = withCallCount(multiply);console.log(countedMultiply(2, 3)); // should log count 1/* Expected output:[COUNT] Function multiply called 1 times6 */console.log(countedMultiply(4, 5)); // should log count 2/* Expected output:[COUNT] Function multiply called 2 times20 */console.log(countedMultiply(6, 7)); // should log count 3/* Expected output:[COUNT] Function multiply called 3 times42 */
Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.