lundi 28 novembre 2016

Convert If-Else statement to Switch Statement

I recently completed a problem in CodeWars using an if-else statement, but I wanted to retry it and use a switch statement instead. Too bad that it is not working the way that I thought it would!

The problem I am solving is to take in a distance(s) that an Ironman triathlon athlete has completed and return an object that shows a key based on whether the athlete should be Swimming, Biking or Running with a value of the length of the race to go.

My If-Else Solution:

function iTri(s) {  
  var triLength = 140.60;  
  var result = {};  
  var str = ' to go!';  
  var lengthLeft = (triLength - s).toFixed(2);  

  if (s === 0) {
    return 'Starting Line... Good Luck!';
  } else if (s <= 2.4) {
    result.Swim = lengthLeft + str;
  } else if (s <= 114.4) {
    result.Bike = lengthLeft + str;
  } else if (s < 130.60) {
    result.Run = lengthLeft + str;
  } else if (s < 140.60) {
    result.Run = 'Nearly there!';
  } else {
    return 'You\'re done! Stop running!';
  }
  return result;
  }

The (non-working) Switch statement:

function iTri(s){
  let tri = (2.4 + 112 + 26.2).toFixed(2);
  let left = tri - s;
  let str = ' to go!'
  let result = {};

  switch(s) {
    case (s === 0):
      return "Starting Line... Good Luck!";
      break;
    case (s <= 2.4):
      result.Swim = left + str;
      return result;
      break;
    case (s <= 114.4):
      result.Bike = left + str;
      return result;
      break;
    case (s <= 130.60):
      result.Run = left + str;
      return result;
      break;
    case (s < 140.60):
      result.Run = 'Nearly there!';
      return result;
      break;
    default:
      return 'You\'re done! Stop running!';
  }
}

These are the tests:

Test.describe("Example tests",_=>{
Test.assertSimilar(iTri(36),{'Bike':'104.60 to go!'});
Test.assertSimilar(iTri(103.5),{'Bike':'37.10 to go!'});
Test.assertSimilar(iTri(2),{'Swim':'138.60 to go!'});
});

And the Output:

✘ Expected: '{ Bike: \'104.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Bike: \'37.10 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Swim: \'138.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''  

Also is it worth it to convert it to a switch statement? What are benefits/drawbacks of doing it as if/else vs switch?

All help is appreciated!

Aucun commentaire:

Enregistrer un commentaire