Using a Proxy for Debug Console (Class)
This time with a class.
by MegaScience
JavaScript
class dM {
constructor(c) {
let conf = {
debug: true
};
switch (typeof c) {
case 'object':
if (typeof c.debug === 'undefined')
c.debug = false;
conf = c;
break;
case 'boolean':
conf.debug = c;
break;
case 'undefined':
default:
// Use default.
}
return new Proxy(a => {
//console.log('Input:\n' + JSON.stringify(a));
if (conf.debug) {
if (typeof a.obj[a.type] !== 'undefined')
return a.obj[a.type](...a.args);
else
return false; // Yikes.
}
}, this);
}
get (t, p) {
return (...x) => t({
obj: p in t ? t : console,
type: p,
args: x
})
}
has (t, p) {
return p in t || p in console
}
apply (t, tA, x) {
if (typeof x[0] === 'object' && ('obj' in x[0] && 'type' in x[0] && 'args' in x[0])) {
//console.log(JSON.stringify(x));
x[0].args.push(...x.slice(1));
return t(x[0]);
}
else return t({
obj: console,
type: 'log',
args: x
})
}
}
let config = {
debug: true
};
let dMsg = new dM(config);
dMsg.foo = x => console.error(x);
dMsg.log('Test');
dMsg.warn('Tester');
config.debug = false;
dMsg.foo('Testie');
config.debug = true;
//dMsg.log(dMsg.toString());
dMsg('cat');
dMsg({obj: console, type: 'warn', args: ['toilet', 'face']}, 'meow', 'woof');