Problem: Add Logging to a Utility Function

easy
15 min
Wrap a pure function with a decorator that logs its input and output.

Problem statement

You’ve got a basic utility function that calculates the square of a number. It’s used across your app, but you want to track what values it receives—and what it returns—without modifying the original function. This is your first step into applying decorators for visibility and traceability.

Goal

Create a withLogging decorator that logs the input arguments and return value of the square function. Then, use it to decorate the original function.

Constraints

  • Do not modify the square function.

  • The withLogging decorator must return a new function.

  • Logging must happen before and after the original function runs.

  • Do not add logging directly inside the square function.

Sample output

The examples below illustrate what the output should look like:

const loggedSquare = withLogging(square);
loggedSquare(5); // should log input and output
/* Expected output:
[LOG] Called with args: [5]
[LOG] Returned: 25 */
loggedSquare(0); // should log input and output
/* Expected output:
[LOG] Called with args: [0]
[LOG] Returned: 0 */

Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.

Problem: Add Logging to a Utility Function

easy
15 min
Wrap a pure function with a decorator that logs its input and output.

Problem statement

You’ve got a basic utility function that calculates the square of a number. It’s used across your app, but you want to track what values it receives—and what it returns—without modifying the original function. This is your first step into applying decorators for visibility and traceability.

Goal

Create a withLogging decorator that logs the input arguments and return value of the square function. Then, use it to decorate the original function.

Constraints

  • Do not modify the square function.

  • The withLogging decorator must return a new function.

  • Logging must happen before and after the original function runs.

  • Do not add logging directly inside the square function.

Sample output

The examples below illustrate what the output should look like:

const loggedSquare = withLogging(square);
loggedSquare(5); // should log input and output
/* Expected output:
[LOG] Called with args: [5]
[LOG] Returned: 25 */
loggedSquare(0); // should log input and output
/* Expected output:
[LOG] Called with args: [0]
[LOG] Returned: 0 */

Good luck trying the problem! If you’re unsure how to proceed, check the “Solution” tab above.

Node.js
function square(n) {
return n * n;
}
// Your code here
// Example usage
const loggedSquare = withLogging(square);
loggedSquare(5); // should log input and output
/* Expected output:
[LOG] Called with args: [5]
[LOG] Returned: 25 */
loggedSquare(0); // should log input and output
/* Expected output:
[LOG] Called with args: [0]
[LOG] Returned: 0 */