Anna Riekic
Anna Riekic

Reputation: 738

re-write ifelse to switch

How would I go about re-writing this ifelse to a switch?

var d = document,
    a = 'foo',
    b = 'bar',
    c = 'foobar';

if (d.URL.indexOf(a) != -1 || d.URL.indexOf(b) != -1)
{

    // do this

}
elseif(d.URL.indexOf(c) != -1)
{

    // do something else

}

it goes on for about 10 more ifelse which is why i'd prefer to change it to switch

I've searched for answers and found nothing so tried this:

function io(i)
{
    d.URL.indexOf(i) != -1;
}

switch (io())
{
case a:
case b:
    // do this
    break;
case c:
    // do this
    break;
}

and a few variations of the same thing but I'm very much a JS novice and so knew I was probably wrong (which I was).

Upvotes: 1

Views: 84

Answers (1)

Evan
Evan

Reputation: 825

I think the best thing to do here would be to actually create an array of objects with their functions, then you would just cycle through that array using every. Here's some demonstration code using your above example:

var choices = [
  {
    value: foo,
    fn: function () { // do this }
  },
  {
    value: 'foobar',
    fn: function () { // do something else }
  }
];
choices.every( function( choice ) {
  if ( document.URL.indexOf( choice.value ) !== -1 ) {
    choice.fn();
    return false;
  } else return true;
});

If you have functions you know will be used multiple times, you just create them outside of the array and assign them to the fn key of multiple objects. By using return true when you don't encounter it, it'll keep moving through the array, then when it hits one where it's true, it'll return false and end the every function.

Upvotes: 1

Related Questions