Skip to content

Instantly share code, notes, and snippets.

@CedricSch
Last active June 2, 2021 21:16
Show Gist options
  • Save CedricSch/0c66dee0297df3bb61041570beda811d to your computer and use it in GitHub Desktop.
Save CedricSch/0c66dee0297df3bb61041570beda811d to your computer and use it in GitHub Desktop.
Exercise 8.2 Timestamped logs
function createConsoleProxy(console) {
return new Proxy(console, {
get: (target, property) => {
const proxyFunctionNames = ["log", "error", "debug", "info"];
if (proxyFunctionNames.includes(property)) {
return function (...argumentList) {
const isoDate = new Date().toISOString();
// Every argument after argumentList[0] will be used as substitution values
const newMessage = `${isoDate}: ${argumentList[0]}`;
return target[property](newMessage, ...argumentList.slice(1));
}
}
return target[property];
}
});
}
// To test property access
console.logMessage = "I´m a log message. %s";
console.infoMessage = "I´m a info message. %s";
console.debugMessage = "I´m a debug message. %s";
console.errorMessage = "I´m a error message. %s";
// Create that ....
const consoleProxy = createConsoleProxy(console);
// Test this stuff
consoleProxy.log(consoleProxy.logMessage, "Test")
consoleProxy.info(consoleProxy.infoMessage, "Test")
consoleProxy.debug(consoleProxy.debugMessage, "Test")
consoleProxy.error(consoleProxy.errorMessage, "Test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment