8

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']);
4
  • What have you tried? Hint: typeof key == 'string' Commented May 20, 2013 at 3:34
  • i thinks its better to use === instead of == or so i have readed Commented May 20, 2013 at 3:35
  • 1
    @JuanAntonioOrozco typeof always returns a string, and I'm comparing it to a string. === is superfluous, since the types are guaranteed to match already. Commented May 20, 2013 at 3:36
  • @Kolink Thanks for the link. Huge eye-opener. Commented May 20, 2013 at 5:42

4 Answers 4

20

This post is old, but here is a pretty good tip:

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Same idea as the accepted answer but more elegant. Thanks!
9
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.

1 Comment

Well except that the original code handled only strings, so now you converted something that works into something that doesn't. But presumably the OP can take your idea and make it work.
0

you could use typeof to check for the type of your argument and proceed accordingly, like

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

Comments

-1

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

In the simplest sense:

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

So that

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

Ideally, you may want to tolerate null, undefined, empty-string, empty-array (and still keep a convenient one-liner):

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

So that also

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

You may want to interpret null/empty/undefined differently, but for consistency, this method converts those to an empty array, so that downstream code does not have to check beyond array-having-elements (or if iterating, no check necessary.)

This may not be terribly performant, if that's a constraint for you.

In your usage:

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 */
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.