// example function where arguments 2 and 3 are optional | |
function example( err, optionalA, optionalB, callback ) { | |
// retrieve arguments as array | |
var args = []; | |
for (var i = 0; i < arguments.length; i++) { | |
args.push(arguments[i]); | |
} | |
// first argument is the error object | |
// shift() removes the first item from the | |
// array and returns it | |
err = args.shift(); | |
// last argument is the callback function. | |
// pop() removes the last item in the array | |
// and returns it | |
callback = args.pop(); | |
// if args still holds items, these are | |
// your optional items which you could | |
// retrieve one by one like this: | |
if (args.length > 0) optionalA = args.shift(); else optionalA = null; | |
if (args.length > 0) optionalB = args.shift(); else optionalB = null; | |
// continue as usual: check for errors | |
if (err) return callback(err); | |
// for tutorial purposes, log the optional parameters | |
console.log('optionalA:', optionalA); | |
console.log('optionalB:', optionalB); | |
/* do your thing */ | |
} // example() | |
// invoke example function with and without optional arguments | |
example(null, function (err) { /* do something */ }); | |
example(null, 'AA', function (err) {}); | |
example(null, 'AAAA', 'BBBB', function (err) {}); |
This comment has been minimized.
This comment has been minimized.
Can we optimize the for loop by replacing it with |
This comment has been minimized.
This comment has been minimized.
I had to remove undefined elements from the array as I kept on getting args = args.filter(function (val) {
return val !== undefined;
}); |
This comment has been minimized.
This comment has been minimized.
@dandv |
This comment has been minimized.
This comment has been minimized.
nice. thanks. |
This comment has been minimized.
This comment has been minimized.
@dandv why not just |
This comment has been minimized.
This comment has been minimized.
How do you know if optionalA or optionalB is intended? If your pattern is Or have I missed something? |
This comment has been minimized.
This comment has been minimized.
@adrianblynch That's only the case if If the signature is Long Story Short: design your function to require |
This comment has been minimized.
This comment has been minimized.
Cool. Thanks! |
This comment has been minimized.
This comment has been minimized.
I get |
This comment has been minimized.
This comment has been minimized.
thanks |
This comment has been minimized.
This comment has been minimized.
Thank you @klovadis and @rossipedia ! |
This comment has been minimized.
mercy