Truncate a string- Is this a bug?

I’m really struggling with the algorithm scripting challenges and most of the time I just go and look up the solution and then I understand from there how to sort out the problem and what the code does. I even took a course on udemy on algorithm scripting which gave me a better idea about algorithms and how to go about solving them but I’m still struggling.

Now on this algorithm I think there is a bug because I can’t pass this challenge even if I copy and paste code from solutions here on the forum. The first 2 tests don’t pass which is:

truncateString(“A-tisket a-tasket A green and yellow basket”, 8) should return “A-tisket…”.
truncateString(“Peter Piper picked a peck of pickled peppers”, 11) should return “Peter Piper…”.

I think the first one where the str lenght is 8 can never return “A-tisket…” that would be a str length of 11 since the “…” is included in the length.
Then same situation on test 2, with the “…” included equals a length of 14 and that test can also never pass.

[spoiler]function truncateString(str, num) {
  // Clear out that junk in your trunk
  if (str.length > num && num > 3) {
    return str.slice(0, (num - 3)) + '...';
  }
   else if (str.length > num && num <= 3) {
    return str.slice(0, num) + '...';
  } 
  else {
    return str;
  }
}

truncateString("A-tisket a-tasket A green and yellow basket", 11);[/spoiler]

Basic Algorithm Scripting: Truncate a String

Hi, here is the code I tried.

function truncateString(str, num) {
  // Clear out that junk in your trunk
  if (str.length > num && num > 3) {
    return str.slice(0, (num - 3)) + '...';
  }
   else if (str.length > num && num <= 3) {
    return str.slice(0, num) + '...';
  } 
  else {
    return str;
  }
}

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

Yes that’s what I cant understand. the chalenge says: Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a … ending.

On the test1 the maximum string length is specified as 8…which should return > “A-tis…”

but the test says it should return > “A-tisket…” which is a length of 11.

oh i think you are misunderstanding. The number is the max allowed for the given string, not for the truncated string!

truncateString(“A-tisket a-tasket A green and yellow basket”, 8) should return “A-tisket…”.

The truncated string if you notice, has 8 chars from the original string plus …
That is what they meant. Hope this helps.

Yes looks like I’m misunderstanding. Thanks I’ll try again

My goodness :smile: I just had to take out the -3 at the first if statement.

problem solved thanks.

2 Likes
  // Clear out that junk in your trunk
  if (str.length > num && num > 3) {
    return str.slice(0, num) + '...';
  }
   else if (num <= 3) {
    return str.slice(0, num) + '...';
  } 
  else {
    return str;
  }
}

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