I'm in the process of building a wrapper library for quite a large service so that the team that I'm working with has an easier time developing using this service.
Basically, one of the API calls is called "subscribe" so that the program subscribes to one or more items (in order to track its changes). The API call takes 1 argument. The documentation shows this:
I did figure out how to use optional parameters, but I can't figure out to make an "either x or y" type of method in javascript.
Simpler may be to make it a variadic function by using a "rest parameter". You could define two parameters, the first required and the rest parameter allowing zero or more.
function subscribe(item, ...items) {
// item is required
// items may be zero or more additional items
}
You don't actually need two parameters, except perhaps for documentation to more clearly show a required argument.
Then they can call it with individual arguments, or if they already have an array, they can use that using spread syntax.
function subscribe(item, ...items) {
console.log("Found: %s, Then: %s", item, items);
}
subscribe("one", "two", "three");
var my_items = ["one", "two", "three"];
subscribe(...my_items);
You could check the parameter and convert single value to an array and work with that array.
function fn(parameter) {
return (Array.isArray(parameter) ? parameter : [parameter]).map(a => 'item' + a);
}
console.log(fn(1));
console.log(fn('abc'));
console.log(fn([3, 4]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With