Created
August 16, 2020 14:23
-
-
Save paviad/73fbdaa298e103b5bd61a93eb41f235e to your computer and use it in GitHub Desktop.
Monkey-patch `console.log` to print JSON versions of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ___console_log = console.log; | |
var ___seen = []; | |
var ___skipCycles = (key, val) => { | |
if (val != null && typeof val == 'object') { | |
if (___seen.indexOf(val) >= 0) { | |
return; | |
} | |
___seen.push(val); | |
} | |
return val; | |
}; | |
console.log = (message?: any, ...optionalParams: any[]) => { | |
const jsonParams = optionalParams.map(r => { | |
if (typeof (r) === 'object') { | |
___seen = []; | |
return JSON.stringify(r, ___skipCycles); | |
} else { | |
return r; | |
} | |
}) | |
___seen = []; | |
const jsonMessage = typeof (message) === 'object' ? JSON.stringify(message, ___skipCycles) : message; | |
___console_log(message, ...optionalParams); | |
___console_log(jsonMessage, ...jsonParams); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment