Using a Proxy for Debug Console

Creating a debug-only console extension via Proxy.

by MegaScience

JavaScript

const c = {
  debug: true
};
const d = config => new Proxy(a => {
	if((typeof config !== 'undefined' && ((typeof config === 'object' && config.debug) || (typeof config === 'boolean' && config))) && typeof a.obj[a.type] !== 'undefined')
		return a.obj[a.type](...a.txt)
}, {
	get: (t, p) => (...x) => t({
		obj: p in t ? t : console,
		type: p,
		txt: x
	}),
	//set: (t, p, v, r) => console[p] = v,
	has: (t, p) => p in t || p in console,
	apply: (t, tA, x) => {
		if(typeof x[0] === 'object' && ('obj' in x[0] && 'type' in x[0] && 'txt' in x[0])) return t(x[0])
		else return t({
			obj: console,
			type: 'log',
			txt: x
		})
	}
});
const dMsg = d(c);
dMsg.warn(1, 2, 3);
dMsg('cats', 'dogs');
dMsg({obj: console, type: 'warn', txt: ['toilet', 'face']});
dMsg({obj: console, car: 'warn', txt: ['toilet', 'face']});
dMsg(JSON.stringify({obj: console, car: 'warn', txt: ['toilet', 'face']}));
dMsg.toilet = txt => alert(txt);
dMsg.toilet('Mom');
dMsg.killMe = x => document.body.innerHTML += x;
dMsg.killMe('poop');
config.debug = false;
dMsg.killMe('pee');
config.debug = true;
dMsg(('log' in dMsg) + '\n' + ('pocket' in dMsg) + '\n' + ('killMe' in dMsg));