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.
You can find the solution at: https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string/
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;
}
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
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!