Skip to content

Instantly share code, notes, and snippets.

@mattsnider
Last active October 8, 2017 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattsnider/5137847 to your computer and use it in GitHub Desktop.
Save mattsnider/5137847 to your computer and use it in GitHub Desktop.
JavaScript function for annotating other JavaScript
function annotate(fnToAnnotate) {
// already annotation aware, use the original annotation chain
if (fnToAnnotate.by) {
return fnToAnnotate;
}
var aAnnotationChain = [fnToAnnotate];
function applyChainFunctions(fn) {
fn.by = function(fnAnnotation, arg1, /*...*/ argN) {
var fnToAnnotate = aAnnotationChain[aAnnotationChain.length - 1],
fnExecutedAnnotation = function () {
/*
Replace the annotation function in the args list,
with the function to annotate. This is a nice little hack
to allow us to call the annotation function using apply, passing
the function to annotate as the first argument, followed by
all the other arguments that were originally passed to ``by``.
*/
arguments[0] = fnToAnnotate;
return fnAnnotation.apply(this, arguments);
}.apply(this, arguments);
aAnnotationChain.push(fnExecutedAnnotation);
return applyChainFunctions(fnExecutedAnnotation);
};
return fn;
}
return applyChainFunctions(fnToAnnotate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment