Last active
January 22, 2025 18:42
-
-
Save brianarn/8951284 to your computer and use it in GitHub Desktop.
Module to wrap `console.group` around all methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A simple object with some methods, | |
// which throw errors when bad arguments are passed. | |
var maths = { | |
square : function (value) { | |
// Validity checking | |
if (arguments.length !== 1) { | |
throw new Error('square: Requires one and only one argument'); | |
} | |
if (typeof value !== 'number') { | |
throw new Error('square: Requires numeric argument'); | |
} | |
// Square it! | |
return value * value; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function will wrap all methods on an object | |
// with detailed logging information. | |
function wrapper (toWrap, identifier, collapse) { | |
// Determine how we're grouping | |
var grouping = collapse ? 'groupCollapsed' : 'group'; | |
// Get all keys of our method and iterate over them | |
var methods = Object.keys(toWrap); | |
methods.forEach(function (method) { | |
// Get the original method | |
var oldMethod = toWrap[method]; | |
// If it's not a function, we're done, skip it | |
if (typeof oldMethod !== 'function') { return; } | |
// Create our wrapped version! | |
toWrap[method] = function wrapped () { | |
var groupName = identifier + ': ' + method; | |
console[grouping](groupName); | |
console.log('%s args: %o', method, arguments); | |
try { | |
var value = oldMethod.apply(this, arguments); | |
console.log('%s return value: %o', method, value); | |
return value; | |
} catch (e) { | |
console.error('%s error: %o', method, e); | |
} finally { | |
console.log('%s: Exiting', method); | |
console.groupEnd(groupName); | |
} | |
}; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment