Skip to content

Instantly share code, notes, and snippets.

@joeyred joeyred/debug.js
Created Nov 30, 2016

Embed
What would you like to do?
A little debugging object.
/**
* Controls whether debug functions have any output to console.
* @type {Boolean}
*/
var DEBUG_IS_ENABLED = true;
/**
* Debug constructor
* @method Debug
* @param {string} objectName The name of the parent object of all logged data
*/
function Debug(objectName) {
this.objectName = objectName;
}
Debug.prototype = {
constructor: Debug,
valueType: function(value) {
return typeof value;
},
outputObjectParent: function() {
console.log('%c ' + this.objectName, 'color: green');
},
/**
* Check if function has been called and what it returned.
* @method function
* @param {string} functionName Name of the function called.
* @param {boolean/string} output The return of the function, or false.
*/
functionReturn: function(functionName, output) {
// Check if debug mode is enabled.
if (DEBUG_IS_ENABLED) {
this.outputObjectParent();
// If the function has no return, then just say the function was called,
if (output === 'undefined') {
console.log(functionName + ' has been called. Function has no return');
// Else, log out the function being called along with its return.
} else {
console.log(functionName + ' has been called. Returned: ' + output);
}
}
},
/**
* Output values within a function to console.
* @example
* // Will log to console:
* // Within foobar:
* // foo is: 5 (Number)
* // bar is: 22 (Number)
* function foobar() {
* var foo = 5;
* var bar = 22;
* Debug.value('foobar',
* {foo: foo, bar: bar}
* );
* }
* @method value
* @param {string} functionName Name of function the value reside in.
* @param {Object} values Object with keys matching variable names to be logged.
*/
values: function(functionName, values) {
// Check if debug mode is enabled.
if (DEBUG_IS_ENABLED) {
this.outputObjectParent();
console.log('Within ' + functionName + ':');
// Loop through values within the function.
for (var key in values) {
if ({}.hasOwnProperty.call(values, key)) {
// Log key and it's value in a readable fashion.
console.log(key + ' is: ', values[key], ' (' + this.valueType(values[key]) + ')');
}
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.