Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript method to accept a string or an array of strings

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:

  • (string, required) Name identifier
  • OR (string, required) ID identifier
  • OR (array, optional) A JSON array of Name or ID identifiers

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.

like image 774
Rachelle Avatar asked Dec 07 '25 22:12

Rachelle


2 Answers

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);
like image 98
spanky Avatar answered Dec 10 '25 11:12

spanky


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; }
like image 43
Nina Scholz Avatar answered Dec 10 '25 12:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!