Skip to content

Instantly share code, notes, and snippets.

@co3moz
Last active March 29, 2016 15:37
Show Gist options
  • Save co3moz/abaf031385c426b2f660 to your computer and use it in GitHub Desktop.
Save co3moz/abaf031385c426b2f660 to your computer and use it in GitHub Desktop.
Javascript function parameter hooker
Function.prototype.getParameters = function () {
return this.parameters || (this.parameters = /function *(?:.*?)\((.*?)\)/.exec(this + "")[1].split(/,/g).map(Function.prototype.call, String.prototype.trim));
} // https://gist.github.com/co3moz/b6bc4bbfa825b60c3812
Function.prototype.hook = function(t, o) {
(o || (o = t, t = this));
return this.apply(t, this.getParameters().map(function(p) { return o[p] }));
}
@co3moz
Copy link
Author

co3moz commented Mar 24, 2016

example

(function(myVariable, soAnotherOne) { console.log(myVariable, soAnotherOne); }).hook({soAnotherOne: 1, myVariable: 2});
// prints "2 1"

(function(soAnotherOne, myVariable) { console.log(myVariable, soAnotherOne); }).hook({soAnotherOne: 1, myVariable: 2})
// prints "2 1" too

we expect that all parameters hooked to object. even we change the order of parameters

@co3moz
Copy link
Author

co3moz commented Mar 29, 2016

example 2

function MyLibrary(callback) {
  return callback.hook({req: {..} res: {..}, next: (function() {..})});
}
MyLibrary(function(res) { // no need req
  res.send("ok");
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment