Last active
July 31, 2016 22:32
-
-
Save leigh-johnson/070159d3fd780d6d8da6e13625234bb3 to your computer and use it in GitHub Desktop.
Functional monkey patching in javascript
This file contains hidden or 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
// 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