user1966211 user1966211 - 4 months ago 10
Javascript Question

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]();
}
};


What I need is that the parameter should be able to accept an array or a string, and should work either way.

Sample function calls:

showRegion('phoneNumberRegion');
showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion']);

Answer
var showRegion = function(key) {
    if (typeof key === 'string')
         key = [key];
    if (key in regionOptions) {
       ...

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

Comments