Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode array elements into comma-separated arguments (Node.js)

Say I have a function that takes an arbitrary number of arguments (the last is callback):

xxx.create ('arg1', 'arg2', ..., 'arg10', callback) {
    ...
}

But it's ugly. I want to be able to extract 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.

Thanks.

like image 888
Pooria Azimi Avatar asked Mar 05 '26 04:03

Pooria Azimi


1 Answers

You're looking for Function.apply.

var args = ['arg1', 'arg2', ..., 'argN'];
xxx.create.apply(xxx, args.concat(callback)) {
    // ...
}

I used Array.concat so as to not mutate the original args array. 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 wanted to use a wrapper instead of exposing the Function.apply call:

function create_wrapper() {
    xxx.create(xxx, arguments);
}

// then

create_wrapper('arg1', 'arg2', ..., 'argN', callback);

will do the job.

like image 132
Matt Ball Avatar answered Mar 08 '26 21:03

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!