Dexygen
Dexygen

Reputation: 12561

How to best pass optional function arguments that are nearly always the same

What's the best way to pass an optional argument that is nearly always the same? Case in point is Javascript's parseInt function; the second argument for radix is optional, but to avoid a string beginning with a zero being treated as octal, it is generally recognized good practice to always specify 10 as the second argument. Fair enough, so I'm wondering, how to best deal with this situation; specifically, should I create a convenience function, such as parseBaseTenInt(str), that just returns parseInt(str, 10)? I've inherited one file of code with about 10 calls to parseInt without the second argument, and creating the convenience function will subsequently allow me to do a simple replacement of parseInt with parseBaseTenInt. However I can conceive of drawbacks to the convenience function, particularly it not being used by other developers. Because it's just 1 file right now, and I will the primary developer moving forward, it wouldn't be too inconvenient to just add the second argument to all the parseInt function calls.

Upvotes: 2

Views: 1873

Answers (4)

Gumbo
Gumbo

Reputation: 655229

You can either check how many arguments have been passed using arguments.length inside the function.
Or you set default values for each variable by using the || operator:

function foo(bar, baz) {
    bar = bar || "default";
    baz = baz || 0;
    return bar + ", " + baz;
}
foo();                 // "default, 0"
foo("some string");    // "some string, 0"
foo("some string", 1); // "some string, 1"

Upvotes: 1

chills42
chills42

Reputation: 14513

We use a lot a functions that apply a default if the passed value is null.

// base defaults to 10
function ParseInteger(str,base)
{
    if(base==null)
        base=10;
    return parseInt(str,base);
}

Upvotes: 1

Depending on the number of parameters you might want to Introduce Parameter Object along with your convenience function. Then you can set defaults for your parameter object and only set the properties that vary when you use the function.

Upvotes: 0

gkrogers
gkrogers

Reputation: 8356

I'd go with your solution - wrap it in a suitably-named function, keep it's behaviour/calling convention consistent with the library function, and use the wrapper function.

Upvotes: 1

Related Questions