Solution: Add Logging to a Utility Function
Explore how to apply the decorator pattern to add logging to a pure utility function in Node.js. This lesson helps you understand wrapping functions to log input arguments and return values without altering the original function, enhancing traceability while preserving core behavior.
We'll cover the following...
We'll cover the following...
Solution explanation
Lines 1–3:
square(n)is a pure utility function that simply returnsn * n. It’s untouched and unaware of logging.Lines 6–13:
withLogging(fn)is a functional decorator. It wraps the original function:Logs the arguments before calling
fn(...). ...