Is this code right?

Is this code right?
0

#1

While doing the following exercise from Free Code Camp = https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string I stumbled upon this solution.

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

}
``````

The interesting thing is that this solution didn’t provide me with passing the challenge. So I looked into the code and I made the following change.

``````function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num && num > 3) {

return str.slice(0, num) + '...';// A fix?

} else if (str.length > num && num <= 3) {

return str.slice(0, num) + '...';

} else {

return str;
}
}

``````

I got the impression that `return str.slice(0, (num - 3)) + '...';` didn’t make much sense since I wanted something that was from that number and beyond and not less. And that was why I wasn’t contemplated with achieving the challenge. So I modified for `return str.slice(0, num) + '...';` and then it worked! I am not sure if this is a bug, or if my logic is right or not. But I would like to know if I am correct, how do I use this to correct in case it is wrong.

Thank you very much. Keep up the good work!

#2

Not sure why it was doing `num - 3` unless the challenge itself changed from a previous iteration and the solution you found was for that previous iteration. Changing it to `str.slice(0,num)` is correct and your logic is sound.

#3

Thank you. Have you checked the answer page? It says exactly that. On the bottom it says about editing (better said not editing, but implementing). So I didn’t know what to do.

#4

I think I know what is going on:

The challenge test wants you to return a string of the given length PLUS “…”
The solution page though assumes (and it may have been this way originally, and just been changed) that the maximum length is the absolute maximum length with “…” included, which is why they used `num - 3`. So, if they stated it as “the truncated string, whether ‘…’ is added to the end or not, must not exceed the given limit” then `num - 3` would be correct. However, as it is, the test is expecting a truncated string of the given length + “…” so using `str.slice(0,num) + "..."` passes.

#5

That makes a lot of sense!

I guess this answer page is some sort of legacy code from the course. I hope they fix this soon, so it won’t cause them problems.

You have a strong case there. Cheers!

#6

This challenge has changed since it was originally written (and since the solution was written). Previously, the “…” was included in the length.