dbg - Create debugging library

This commit is contained in:
n loewen 2023-08-29 11:51:17 -04:00
parent b776951e81
commit a2a79cea46
1 changed files with 80 additions and 0 deletions

80
src/dbg.js Normal file
View File

@ -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();
*/