Skip to content Skip to sidebar Skip to footer

Convert From If Else To Switch Statement

I have the following if, else if, else construct and I am just curious how I could convert such as construct into a switch statement. var emailSubject = email.subject.toLowerCase

Solution 1:

Your example code cannot easily be converted to a switch statement in most languages, nor should it. switch is for comparing a single variable against a range of constant values, whereas your logic requires comparison against non-constant values, with no variable to compare them with. if/else if is the correct construction for your case.

Solution 2:

You can only use case to check a value:

switch(emailSubject){
    case"Subject1": //(emailSubject == "Subject1")//do acct request break;
    case"Subject2": //(emailSubject == "Subject2")//do something elsebreak;
    default:
       //do default 
}

Otherwise you should be using if/else

Solution 3:

Constructs like this are usually crying out for polymorphism...

Play with it here: http://jsbin.com/utilu4/3

var mailHandlers = [

  {
    CanHandleEmail : function(email) {
      return email.subject.toLowerCase().indexOf("account request") >= 0;
    },

    HandleEmail : function(email) {
      alert("do acct req");
    }
  },

  {
    CanHandleEmail : function(email) {
      return email.subject.toLowerCase().indexOf("account pending removal for") >= 0;
    },

    HandleEmail : function(email) {
      alert("do account removal");
    }
  },

  {
    CanHandleEmail : function(email) {
      return email.subject.toLowerCase().indexOf("listserv application") >= 0;
    },

    HandleEmail : function(email) {
      alert("do listserv app");
    }
  },

  {
    CanHandleEmail : function(email) {
      return email.subject.toLowerCase().indexOf("student organization webmaster transfer request") >= 0;
    },

    HandleEmail : function(email) {
      alert("do webmaster xfer");
    }
  },

  {
    CanHandleEmail : function(email) {
      returntrue;
    },

    HandleEmail : function(email) {
      alert("do default");
    }
  }
];

functionHandleEmail(email) {
  for(i=0; i< mailHandlers.length; i++) {
    if(mailHandlers[i].CanHandleEmail(email)){
      mailHandlers[i].HandleEmail(email);
      break;
    }
  }
};

Solution 4:

As mentioned, if/else is best for what you've got.

If, however, you were looking for actual whole subject lines, instead of words within subject lines, you could do something like:

var a = ["account request", "listserv application", "student organization webmaster transfer request"];
switch(a.indexOf(emailSubject)) {
  // ...
}

Solution 5:

Just as a tip: wrap your code in a function and return the value of the match. (You don't have to use else in this case.) If you want to, you could return a code for the match (eg. an int) and use switch/case to perform the action.

Post a Comment for "Convert From If Else To Switch Statement"