Rewriting an if else as a switch

I’m trying to rewrite the if else structure from the 2nd block of code as a switch statement in the first block of code… but I’m missing something. A few of the test cases are still failing.

function truncateString(str, num) {
 
 switch ((str, num)) {
   
    case str.length > num:
      return str;

    case num <= 3:
      str = str.slice(0, num) + "...";

    default:
      str = str.slice(0, num - 3) + "...";
                    }
  return str;
}

truncateString(“Absolutely Longer”, 2);
returns “Absolutely Longe…”
should be returning “Ab…”.

function truncateString(str, num) {
if (str.length <= num) {
    return str;
  } else if (num <= 3){
    return str.slice(0, num) + '...';
  } else {
    
    return str.slice(0, num - 3) + '...';
  }    
}

It’s for the freeCodeCamp.com challenge
https://www.freecodecamp.com/challenges/truncate-a-string

1 Like

Your second case is falling through to the default section.

Be sure to always end each case with a break statement, or a return, to prevent that from happening.

2 Likes

Switches require a break or a return in every case or they will continue to fall through to the next case.

Replace str = with return and you should be good.

I’m still missing something…

Your logic doesn’t solve the challenge

1 Like
function truncateString(str, num) {
  switch ((str, num)) {
    case str.length <= num:
      str = str;
      break;

    case num <= 3:
      str = str.slice(0, num) + "...";
      break;

    default:
      str = str.slice(0, num - 3) + "...";
      break;
  }
  return str;
}

I don’t understand why the first case of str.length is less than or equal to num is ignored… they are both 43
but instead it is still falling through to the default.

truncateString(
“A-tisket a-tasket A green and yellow basket”,
“A-tisket a-tasket A green and yellow basket”.length
);
//should return “A-tisket a-tasket A green and yellow basket”.

https://goo.gl/KCPfzV

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.