One-liner JS debug-logger for recursive function coding exercise

Coding exercise like leetcode, lintcode, hacker rank are just gym rooms for programmers.

But debug your code on your webpage can be horrible.

This is even true when you write recursive functions, which I often do.

So we need a one-liner logger to help our debug. It must be able to inidicate the nested levels of my recursive function. Here it is:

Code for Copy&Paste

var Logger=function(){function t(o,t){this.logKey=o,this.writeLog=t}return t.prototype.log=function(o){var t=null;t="function"==typeof o.toString&&"object"!=typeof o?o.toString():o,this.writeLog({logKey:this.logKey,content:t})},t.prototype.child=function(o){return new t(this.logKey+"."+o,this.writeLog)},t}(),consoleLogger=new Logger("MAIN",console.log);

How to use it?

const logger = consoleLogger; // just for shorter name
logger.log('debug message 1'); // {logKey: "MAIN", content: "debug message 1"}
let level2Logger = logger.child('lv2')
level2Logger.log('debug message 1') // {logKey: "MAIN.lv2", content: "debug message 1"}

As you can see, you will not be confused by the same message if you set a child logger correctly as you pass it into next recursive call.

你可能感兴趣的:(One-liner JS debug-logger for recursive function coding exercise)