Yvon
Yvon

Reputation: 2993

javascript: common commands in switch statement

I have a situation using switch to filter out say a big array. It goes like

var myArray = ['a','b','c','d'];
$.each( myArray, function (ind, elem) {
    switch (true) {
        case (elem === 'a'):
            // do something to a
            break;
        case (elem === 'b'):
            // do something to b (but not to a)
            break;
        always: // do this if we have done something
            alert('we have done something!');
    }
});

So I expect alerts for a and b but not for c or d.

Is there any way to achieve this?

Upvotes: 2

Views: 209

Answers (1)

Pointy
Pointy

Reputation: 413826

First, I would write that switch more idiomatically:

switch (elem) {
  case 'a':
    // 'a' code
    break;
  case 'b':
    // 'b' code
    break;
  default:
    // anything else
 }

Note that it's the default label that you're looking for. If, on the other hand, you just want to do something only when there's a match, then a switch may not be the cleanest approach, because there's not a good way to include boilerplate code for each case (other than to just copy/paste).

You could use separate functions, and have the functions be constructed such that they set a flag:

  var didSomething = false;

  function doSomething(fn) {
    fn();
    didSomething = true;
  }

  switch (elem) {
    case 'a':
      doSomething(function() { /* 'a' code */ });
      break;
    case 'b':
      doSomething(function() { /* 'b' code */ });
      break;
   }

   if (didSomething) {
     alert("did something");
   }

Alternatively, you could make a map:

   var actions = {
     'a': function() { /* 'a' code */ },
     'b': function() { /* 'b' code */ }
   };

   if (actions[elem]) {
     actions[elem]();
     alert("did something");
   }

Upvotes: 5

Related Questions