Using a Proxy for Debug Object Functions (Class)
This time with a class.
by MegaScience
JavaScript
class debugOnly {
constructor(debug, obj = console, defaultProp = 'log') {
this.obj = obj;
this.defaultProp = defaultProp;
let config = { debug: true };
switch(typeof debug) {
case 'object':
if(typeof debug.debug === 'undefined')
debug.debug = false;
config = debug;
break;
case 'boolean':
config.debug = debug;
break;
case 'undefined':
default:
// Use default.
}
return new Proxy(data => {
let o = data.prop in obj ? obj : (data.prop in this ? this : false);
if(o === false) return undefined;
if(config.debug) {
if(typeof o[data.prop] === 'function')
return o[data.prop](...data.args);
else
return o[data.prop];
}
return false;
}, this);
}
get (target, prop) {
return (...args) => target({
prop: prop,
args: args
})
}
has (target, prop) {
return prop in this || prop in this.obj
}
apply (target, thisArg, args) {
if (typeof args[0] === 'object' && ('prop' in args[0] && 'args' in args[0])) {
args[0].args.push(...args.slice(1));
return target(args[0]);
}
else return target({
prop: this.defaultProp,
args: args
})
}
}
let config = {
debug: true
};
let dMsg = new debugOnly(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, prop: 'warn', args: ['toilet', 'face']}, 'meow', 'woof');