Javascript function accepts both arrays and strings as parameter

I have this code:

var showRegion = function(key) { if (key in regionOptions) { var entry = regionOptions[key]; var builder = entry.builder; var layoutObj = entry.layoutObj; var viewStarter = entry.viewStarter; var view = new builder(); logger.info('Controller.' + key + ' => CreateAccountLayoutController'); Controller.layout[layoutObj].show(view); view[viewStarter](); } }; 

I need the parameter to be able to take an array or string and should work anyway.

Examples of function calls:

 showRegion('phoneNumberRegion'); showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion']); 
+4
source share
4 answers
 var showRegion = function(key) { if (typeof key === 'string') key = [key]; if (key in regionOptions) { ... 

No need to create code for each case, just convert the key string into an array of one element, and the code for arrays will do for both.

+7
source

This post is old, but here is some pretty good advice:

 function showRegions(keys) { keys = [].concat(keys) return keys } // short way const showRegions = key => [].concat(keys) showRegions(1) // [1] showRegions([1, 2, 3]) // [1, 2, 3] 
+2
source

you can use typeof to check the type of your argument and act accordingly, for example

 var showRegion = function(key) { if( typeof key === 'object') { //its an object } else { //not object } } 
0
source

You can use the fact that string.toString () always returns the same string, and Array.toString () returns a comma-separated string in combination with string.split (',') to accept three possible inputs: convert a string, an array, a comma-delimited string reliably to an array (provided that you do not expect the commas to be part of the values โ€‹โ€‹themselves, and you do not mind the numbers becoming strings).

In the simplest sense:

 x.toString().split(','); 

So,

 'a' -> ['a'] ['a','b'] -> ['a','b'] 'a,b,c' -> ['a','b','c'] 1 -> ['1'] 

Ideally, you can wrap null, undefined, an empty string, an empty array (and still support a convenient one-liner):

 ( (x || x === 0 ) && ( x.length || x === parseFloat(x) ) ? x.toString().split(',') : []); 

So also

 null|undefined -> [] 0 -> ['0'] [] -> [] '' -> [] 

You can interpret the null / empty / undefined value differently, but for consistency, this method converts them to an empty array, so that the downstream code should not check the elements of array-having-elements (or, if iterating, checking is not required.)

This may not be very impressive if this is a limitation for you.

In your use:

 var showRegion = function(key) { key = ( (key || key === 0 ) && ( key.length || key === parseFloat(key) ) ? key.toString().split(',') : []); /* do work assuming key is an array of strings, or an empty array */ } 
-1
source

Source: https://habr.com/ru/post/1481690/


All Articles