I have several functions with the same signature: (user, callback). I'm hitting an API that returns paginated results when the collection is over a certain size - when this happens, I get back a cursor that I can use to fetch the next set, and so on.
My problem: I want to be able to accept an optional 'next' argument. Obviously using 'null' as a placeholder is off the table, and I want to do this without resorting to wrapping my arguments in an object, such as ({user: 'person', next: '12345'}, callback). This seems to be the common pattern for this, but this project is for public use and I think that's an unexpected and weird syntax for people used to similar libraries.
Here's my current solution. I'm not super happy with it and I'm sure there's a better way to accomplish this.
var parseArguments = function (args){
// callback will always be the last argument
var callback = args[args.length - 1];
var next = args.length > 2 ? args[1] : null;
return {callback: callback, next: next};
};
And here's how it's getting used:
this.getSubmissions = function (user, next, callback){
var args = parseArguments(arguments);
var path = user + '/submissions/';
if (args.next){
path += '?next=' + args.next;
}
get(path, args.callback);
};
Which allows me to do the following:
client.getSubmissions('username', function (error, response, body){
// stuff
})
or:
client.getSubmissions('username', 'cursor', function (error, response, body){
// stuff
})
Am I asking for trouble with this? Is there a less clumsy way to go about it?
EDIT: Oops, I should clarify that I'm looking for ES5 compatible solutions. Also, the other suggested answers offer solutions to the default argument problem but don't account for situations where the optional one appears in the middle of two required ones. For example:
function foo(a, b){
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
doesn't help because if I extended this example to fit my use case, I would still end up with my callback falling into the second argument slot whenever the function was called without the optional arg.