Skip to content

Instantly share code, notes, and snippets.

@leigh-johnson
Last active July 31, 2016 22:32
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 leigh-johnson/070159d3fd780d6d8da6e13625234bb3 to your computer and use it in GitHub Desktop.
Save leigh-johnson/070159d3fd780d6d8da6e13625234bb3 to your computer and use it in GitHub Desktop.
Functional monkey patching in javascript
// Remember: With great power comes great responsibility
/* Runtime Hooks */
// Run patcher fn before the original function invocation
// aArgs - array / node list of arguments
function before(fn){
return function(original){
fn.apply(this, aArgs)
return original.apply(this, aArgs)
}
}
// Run patcher fn after the original function invocation
// aArgs - array / node list of arguments
function after(fn) {
return function(original) {
return function() {
var value = original.apply(this, aArgs)
fn.apply(this, aArgs)
return value
}
}
}
// Calls patcher fn accepting original fn invocation as the only argument
// aArgs - array / node list of arguments
function compose(fn){
return function(original){
return function(){
return fn.call(this, original.apply(this, aArgs))
}
}
}
/* Utils */
// Replace an internal method of a class instance
// object - an instance of the class to override (obj)
// method - the method's name (str)
// callback - consume the original method and return something else (fn)
function override(object, method, callback) {
object[method] = callback(object[method])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment