Expand array elements into comma separated arguments (Node.js)
Let's say that I have a function that takes an arbitrary number of arguments (the latter is a callback):
xxx.create ('arg1', 'arg2', ..., 'arg10', callback) {
...
}
But this is ugly. I want to be able to fetch the first few parameters and do something like:
var args = ['arg1', 'arg2', ..., 'arg10']
xxx.create (args.explode(), callback) {
...
}
Of course, I can write a wrapper for xxx.create()
, but I want it to be clean.
Thank.
source to share
You are looking for Function.apply
.
var args = ['arg1', 'arg2', ..., 'argN'];
xxx.create.apply(xxx, args.concat(callback)) {
// ...
}
I used Array.concat
to avoid mutating the original array args
. If that's not a problem, either of these will suffice:
var args = ['arg1', 'arg2', ..., 'argN', callback];
xxx.create.apply(xxx, args) {
// ...
}
// or
var args = ['arg1', 'arg2', ..., 'argN'];
args.push(callback);
xxx.create.apply(xxx, args) {
// ...
}
Now if you want to use a wrapper instead of a call Function.apply
:
function create_wrapper() {
xxx.create(xxx, arguments);
}
// then
create_wrapper('arg1', 'arg2', ..., 'argN', callback);
will do the job.
source to share
The local variable arguments can help here :
foo = function(){
// convert local 'arguments' object to array ...
argsArray = Array.prototype.slice.call(arguments);
// pop the callback off
callback = argsArray.pop();
// the callback alerts the remaining, variable-length arguments list
callback(argsArray);
};
here's a jsfiddle: http://jsfiddle.net/K38YR/
source to share