0

I have a middle ware that looks like this:

function(middleWareData) { // has more args, middleware doesn't know how many
    if(middleWareData.passes()) {
        origFunction(/* call with the rest of the args? */
    }
}

I'm not actually sure the best way to pop off the first argument from arguments then pass the rest to the original function. The original function is very dynamic (it's a connector, either to RabbitMQ which uses 4 arguments, or Redis which uses 2, or a unit test driver which just needs 1) so the middleware doesn't know how many arguments it's actually going to receive.

Using this: var args = Array.prototype.slice.call(args, 1) seems like a good start to get the true arguments. However, I believe I just turned arguments 2 through however many into one argument, that's going to be passed as an array to the first variable. Not what I want. How to do this right?

djechlin
  • 59,258
  • 35
  • 162
  • 290

1 Answers1

0

You pretty much nailed how to get the correct arguments (excluding the first one). To send the arguments array to the next function, you simply have to .apply() the new array to the original function.

apply() is a method of the Function prototype (Function.prototype.apply), so it can be called on any function. It accepts two arguments: the context (or this) for that call, and an Array that will be used for the arguments of that function call. Based on your code, I assumed that the function was run in the global context, so the first argument is set to null.

function(middleWareData) {
    if (middleWareData.passes()) {
        origFunction.apply(null, Array.prototype.slice.call(arguments, 1));
    }
}
Fuzzical Logic
  • 12,947
  • 2
  • 30
  • 58