Last active
March 22, 2021 01:49
-
-
Save mrcoles/425a2940e8820ff3c7aee2c46ad08048 to your computer and use it in GitHub Desktop.
A decorator for wrapping a function in a `console.group(msg)` -> `console.groupEnd()` call.
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
export function groupCollapsedFn<F extends Function>( | |
msg: any, func: F, | |
): F; | |
export function groupFn<F extends Function>( | |
msg: any, func: F, isCollapsed?: boolean | |
): F; |
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
export const groupCollapsedFn = (msg, func) => groupFn(msg, func, true); | |
export const groupFn = (msg, func, isCollapsed) => { | |
// decorated func | |
return function() { | |
// start group | |
console[isCollapsed === true ? "groupCollapsed" : "group"](msg); | |
try { | |
let result = func.apply(this, arguments); | |
if (_isPromise(result)) { | |
// result is promise | |
return result | |
.then(val => { | |
console.groupEnd(); | |
return val; | |
}) | |
.catch(err => { | |
console.groupEnd(); | |
throw err; | |
}); | |
} else { | |
// result is not async | |
console.groupEnd(); | |
return result; | |
} | |
} catch (e) { | |
// error was thrown | |
console.groupEnd(); | |
throw e; | |
} | |
}; | |
}; | |
const _isPromise = x => | |
x && | |
typeof x === "object" && | |
typeof x.then === "function" && | |
typeof x.catch === "function"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This allows you to decorate a JavaScript function such that every time you call it, it starts a
console.group(…)
orconsole.groupCollapsed(…)
and regardless of how the function terminates via any of the following ways, it will safely end the group:Simple example:
NOTE: the example shows it working with promises that run in serial, if you have this on promises that are running in parallel, then it is possible for the grouping to get mixed up.