Skip to content

Instantly share code, notes, and snippets.

@JeffML
Created November 17, 2018 19:52
Show Gist options
  • Save JeffML/5dd22fd6b8dedf6e26e3b9e9f6b7781b to your computer and use it in GitHub Desktop.
Save JeffML/5dd22fd6b8dedf6e26e3b9e9f6b7781b to your computer and use it in GitHub Desktop.
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if (result === null)
result = [];
return result;
}
const log2 = (target, name, descriptor) => {
const original = descriptor.value;
if (typeof original === 'function') {
const paramNames = getParamNames(original)
descriptor.value = function (...args) {
const params = paramNames.reduce((obj, pn, i) => {
obj[pn] = args[i];
return obj;}, {} )
const result = original.apply(this, args);
console.log(`${name}(${JSON.stringify(params)}) = ${result}`)
}
}
}
class MyClass {
@log2
sum(a, b) {
return a + b;
}
}
const instance = new MyClass();
instance.sum(4, 5); // decorator outputs: sum2({"a":4,"b":5}) = 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment