# Completing Algorithms

2016-06-05 Tiffany White

So, the last time I wrote an article here, I was struggling with the Truncate String algorithm.

I took to the forums again and a guy named Chuck told me to delete all the pseudocode. He talked to me about keywords and how to think about what was being asked of me. He broke it down like this:

If the length of str is longer than the value of num then shorten str to be as long as the value of num minus the length of '...'. Unless the value of num is less than or equal to three. In that case, just shorten str to be as long as the value of num. Either way, Then add '...' to the end of str and give it back to us. Otherwise, just give us back str.

Oh wait! Three? ’…’ is three dots! so we can change “the length of ’…’ in our plan into three!:

If the length of str is longer than the value of num then shorten str to be as long as the value of num minus three. Unless the value of num is less than or equal to three. In that case, just shorten str to be as long as the value of num. Either way, then add ’…’ to the end of str and give it back to us. Otherwise, just give us back str.

My code got a little better, but it wasn’t quite right. I went to the Gitter chat. I was struggling with getting the right truncated string. All but two tests were passing.

I got guided in the Gitter chat, but didn’t get the answer given to me, which I really loved. [Tweet ” Completing algorithms without being given the answer is extremely rewarding and satisfying.”] My solution:

function truncateString(str, num) {

if (num < 3) {

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

} else if (str.length < num) {

return str.slice(0, (num - 3)) + "...";

}

return str;

}

truncateString("A-", 1);

## Sometimes, Instructions Are Starting Points, and The Ones Who Guide You Aren’t Always Right

I was reading on one of the Free Code Camp groups about Andrew Charlebois, a guy who took his Free Code Camp skills and in 5 months got a job as a Front-end dev.

I was curious about him— I loved his portfolio and so I hooked up with him on LinkedIn and checked out his Free Code Camp profile.

I looked at his solution for Truncate String and his was elegant. It looked like this:

function truncate(str, num) {

if (str.length <= num)

return str;

if (num <= 3)

return str.substr(0,num) + "...";

return str.substr(0,num-3) + "...";

}