Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icholy/6f8980a33e6dc2e313e7 to your computer and use it in GitHub Desktop.
Save icholy/6f8980a33e6dc2e313e7 to your computer and use it in GitHub Desktop.
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m,
FN_ARG_SPLIT = /,/,
FN_ARG = /^\s*(_?)(\S+?)\1\s*$/,
STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var fnSignature = function (fn) {
var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
args = fnText.match(FN_ARGS);
if (!args) { return []; }
return args[1].split(FN_ARG_SPLIT).map(function (arg) {
return arg.trim();
});
};
var addMagic = function (fn) {
var sig = fnSignature(fn);
sig.forEach(function (arg, i) {
fn[arg] = function () {
var args = [].slice.call(arguments).map(function (x) {
return x.toString();
}).join(", ");
console.log(
arg + " (parameter #" + i + ") called with [" + args + "]"
);
return fn;
};
});
};
var fn = function (a, b, c) { };
addMagic(fn);
fn.a(1, 2).b("test").c();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment