Having variable-arg functions

Discuss your code, get questions answered

Having variable-arg functions

Postby oliver » Mon Jul 16, 2012 3:16 am

In JavaScript, you can have functions that take a variable number of arguments.

Say you want a function that can take two arguments but should also work if called with one argument. In that case, some kind of default should apply.

In C++, you'd write a declaration like this:
void myFunc(int start, int end = 1000)
This looks similarly in Java.

In JavaScript, all you have to do is check if a given arg is undefined and act on it appropriately.
Code: Select all
function (start, end) {
    if (end == undefined)
        end = 1000;
    ...
}

or, in one line
Code: Select all
function (start, end) {
    end = (end == undefined ? end : 1000);
    ...


Some people like to write
Code: Select all
function (start, end) {
    end = end || 1000;
    ...

which is equivalent to
Code: Select all
function (start, end) {
    end = (end ?  end : 1000);
    ...

Be mindful with those two last approaches, though. They work until you feed in a value of 0: given that value, the default will apply, when this is most likely not the intention. Checking for != 0 isn't the same as checking for "undefined". That is, this will work fine unless you're passing in a value of zero *and* your default is nonzero.


In RPL

The downside of using variable arg functions is that RPL, by its very nature, doesn't deal with multi arg functions. So, if you plan on scripting your JavaScript with RPL, you haven't gained anything. Following the example, you'd still have to provide two args in RPL.

You can, of course, populate a varying number of arguments in an array and have your called functions (in RPL or JavaScript), use the individual components of the array and deal with a varying number of them.

Also, special in RPL+, you may construct and pass a JS object that could contain any number of named arguments.
For example:
Code: Select all
    ≪ 20 1.2 {"type": "parametric", "show": true } myRPLorJSFunction ≫


RPL+ may in the future support a means to do generic variable-argument calls.
oliver
Site Admin
 
Posts: 433
Joined: Sat May 01, 2010 2:11 pm

Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest

cron