views:

90

answers:

4

My question is, is there a way to make this code more efficient or write it in a simple way? javascript by the way.

switch (tempvar1) {
  case 1:
    currentSlide = 'slide1';
    showaslide('ppslide1');
    break;
  case 2:
    currentSlide = 'slide2';
    showaslide('ppslide2');
    break;
  case 3:
    currentSlide = 'slide3';
    showaslide('ppslide3');
    break;
  case 4:
    currentSlide = 'slide4';
    showaslide('ppslide4');
    break;
  case 5:
    currentSlide = 'slide5';
    showaslide('ppslide5');
    break;
  case 6:
    currentSlide = 'slide6';
    showaslide('ppslide6');
    break;
  // 20 total cases
}
+7  A: 
currentSlide = 'slide' + tempvar1;
showaslide('ppslide' + tempvar1);
Seattle Leonard
+2  A: 

How about:

currentSlide = 'slide' + tempvar1;
showaslide('ppslide' + tempvar1);
JW
+8  A: 

This can be done much more elegant:

if (tempvar1 <= 20) {
  currentSlide = 'slide' + tempvar1;
  showaslide('ppslide' + tempvar1);
}

In JavaScript, integer values are automatically converted to strings if combined with them. The + operator concatenates the strings.

EDIT: Followup on your comment question to check if tempvar is an integer. One possiblity to check this (there are also other modifications to round up the code):

if (!isNaN(parseInt(tempvar1))) {
  if (tempvar1 >= 1) && (tempvar1 <= 20) {
    currentSlide = 'slide' + tempvar1;
    showaslide('ppslide' + tempvar1);
  } else {
    // Some error handling or default case here if needed
    // thx to eyelidlessness ;)
  }
}

The first if statement tries to treat tempvar1 as an integer value and only continues if this works.

schnaader
Ah, it's so simple. How would I make it say (if(tempvar1 is an integer and is less than 20))? or is a check like that not necessary because if they messed with any part of your code they could mess with it all? is javascript very unsecure?
Derek
+1 for actually implementing the same functionality as in the question (unlike the several other answers which are all identical to one another). One additional point would be that if there is a `default` case, it would be handled in an `else` here.
eyelidlessness
About the necessity of the check: If tempvar1 comes from user input, you should definitely use checks and go for safety. But if tempvar1 is f.e. some loop counter you are fully aware of, this isn't necessary.
schnaader
Is the `parseInt()` call required? In my Rhino console I get `isNaN("3") === false`.
harto
@harto: Hmm.. I'm not sure, I just found much code that does it that way, perhaps `isNaN(tempvar1)` is enough...
schnaader
+3  A: 

You don't need the switch statement:

currentSlide = 'slide' + tempvar1;
showaslide('ppslide' + tempvar1);
Alex - Aotea Studios