Basic Algo Scripting: Truncate a String

Hi everyone! Here’s my solution to the challenge that, to my surprise, passed:

function truncateString(str, num) {
  // Clear out that junk in your trunk
  let newStr = ''

  if(str.length > num) {
    newStr = str.slice(0, num) + "...";
  } else {return newStr = str;}

  return newStr;

truncateString("A-tisket a-tasket A green and yellow basket", 8);

The reason I’m surprised is because I was looking at the solution, trying to understand it while writing my own code, and the solution has 3 outcomes in the if else statement. But I made mine simple. I think it’s too simple I can’t believe it passed. I still don’t understand the solution code completely and I feel bad for going through if I’m missing something important.

Here’s the FCC Challenge Solution link for your reference.

The solution in the guide is for an older and slightly more difficult version of the challenge (it counted the three dots as part of the length). I don’t believe it even works for the current challenge.

I see, I was so confused with that solution. Thanks for clarifying it. :smiley:

Hi @djma777
You will find that it could still be made simpler by just reassigning str=str.slice(0,num)+"…" and just return str by this you may opt not to declare and use “newStr” thus making the code leaner

And if you opt to be super lean, a ternary like this
str.length>num? str=str.slice(0,num)+"…":str=str;
could be great.