Last active
October 8, 2017 16:47
-
-
Save mattsnider/5137847 to your computer and use it in GitHub Desktop.
JavaScript function for annotating other JavaScript
This file contains 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
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