Truncate a String: Alternate Solution

I don’t need help for this challenge, per se.
I came up with an alternate solution to the provided answers (it seemed the most logical way to do it to me), and I am just wondering if there are any drawbacks to the way I did it?

Thanks.

My solution:

function truncateString(str, num) {
var truncStr = str.slice(0, num);
if (num < str.length) {
truncStr += "...";
}
return truncStr;
}

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string

The drawback is if str.length is less than or equal to num, there is no point in creating the string truncStr. You only need to slice if you are going to add the ... anyway.

I think I know what you mean, but two of the requirements for the challenge were:

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”.

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) should return “A-tisket a-tasket A green and yellow basket”.

Only truncated strings were to have the dots, so I had to add the extra code to ‘remove them’ from those two possibilities.

The fact that only truncated strings need to have the dots is exactly the reason you don’t need to slice the original string or add dots on the end unless str.length > num. The algorithm would be:

If str.length is less than or equal to num, then return str.
Otherwise, return the truncated string plus the 3 dots.

There is no reason to slice anything before checking if str.length is less than or equal to num. You can (as you did in your code), but it is an extra step which is not needed if str.length is less than or equal to num. That is why you only take the extra step once you know if str.length is less than or equal to num.

The alternative way of looking at the problem is:

If str.length is greater than num, then return the truncated string plus the 3 dots.
Otherwise, return str.

Okay, I see what you’re saying. I guess I sort of approached it backwards.

Thanks. I appreciate the help – I don’t want to be picking up bad habits so I thought I’d check.

In general, you want to take as few steps as possible to reach the desired outcome. The most important thing is you figured out a way to solve the problem. The fact that you asked for further guidance and learned something else is a bonus.

1 Like