Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Last active March 22, 2021 01:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcoles/425a2940e8820ff3c7aee2c46ad08048 to your computer and use it in GitHub Desktop.
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.
export function groupCollapsedFn<F extends Function>(
msg: any, func: F,
): F;
export function groupFn<F extends Function>(
msg: any, func: F, isCollapsed?: boolean
): F;
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";
@mrcoles
Copy link
Author

mrcoles commented Sep 7, 2018

This allows you to decorate a JavaScript function such that every time you call it, it starts a console.group(…) or console.groupCollapsed(…) and regardless of how the function terminates via any of the following ways, it will safely end the group:

  • synchronously
  • thrown error
  • resolved promise
  • rejected promise

Simple example:

const doThing = groupFn("Doing thing", (index) => {
  console.log(`in Function: ${index}`);
  return Promise.resolve().then(() => {
    console.log(`in Promise: ${index}`);
    return true;
  })
});

doThing(1).then(() => doThing(2));

resulting console.group examples

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment