From a2a79cea4620a4dc58a691a5c613847534242377 Mon Sep 17 00:00:00 2001 From: n loewen Date: Tue, 29 Aug 2023 11:51:17 -0400 Subject: [PATCH] dbg - Create debugging library --- src/dbg.js | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/dbg.js diff --git a/src/dbg.js b/src/dbg.js new file mode 100644 index 0000000..a0806a9 --- /dev/null +++ b/src/dbg.js @@ -0,0 +1,80 @@ +module.exports = class DBG { + /** + * @param ${'warn'|'info'|'debug'|'nitpick'} [level='info'] + **/ + constructor(level = 'info') { + if (this._levels.includes(level)) { + this._level = level; + } else { + throw new Error(`'${level}' is not a valid debug level`); + } + this._levels.forEach((l) => { + this._createLogger(l); + this._createGrouper(l) + this._createGroupEnder(l) + this._createExecer(l) + }); + } + + _levels = ['nitpick', 'debug', 'info', 'warn']; + _shortNames = {'nitpick':'nit', 'debug':'d', 'info':'i', 'warn':'warn'}; + + _createLogger(name) { + const short = this._shortNames[name] + this[short] = (s = '') => { + if (this._lvl2num(name) >= this._lvl2num(this._level)) { + console.log(s); + } + } + } + + _createGrouper(name) { + const short = this._shortNames[name] + this[short + 'Group'] = (s) => { + if (this._lvl2num(name) >= this._lvl2num(this._level)) { + console.group(s); + } + } + } + + _createGroupEnder(name) { + const short = this._shortNames[name] + this[short+'GroupEnd'] = () => { + if (this._lvl2num(name) >= this._lvl2num(this._level)) { + console.groupEnd(); + } + } + } + + _createExecer(name) { + const short = this._shortNames[name] + this[short+'Exec'] = (func) => { + if (this._lvl2num(name) >= this._lvl2num(this._level)) { + func(); + } + } + } + + _lvl2num(lvl) { + return 1 + this._levels.findIndex(l => l === lvl); + } +} + +/* TEST +const dbg = new DBG('nitpick'); +dbg.warnGroup('w'); +dbg.warn('warn'); +dbg.warnGroupEnd(); + +dbg.iGroup('i'); +dbg.i('info'); +dbg.iGroupEnd(); + +dbg.dGroup('d'); +dbg.d('debug'); +dbg.dGroupEnd(); + +dbg.nitGroup('n'); +dbg.nit('nitpick'); +dbg.nitGroupEnd(); +*/ \ No newline at end of file