Algorithm: Reverse String

One of the hardest task to achieve is coding a program that reverses a string. For example, “Greetings from Earth” should return “htraE morf sgniteerG”. This challenge can be seen on @freecodecamp. Requirements include:

Reverse the provided string.

  • create a function that accepts a string and returns a string
  • Your result must be a string.

Sample Code:

function reverseString(str) {
return str;
}
reverseString("hello");

Just like any algorithm, there are multiple ways of executing it. For such a small program such as this, I’ve decided I was going to focus on coding the least amount of lines. After a few seconds, I created this one line beauty.

To program this code, I fundamentally used three built-in JavaScript methods. The methods are split, reverse, and join. Split() essentially takes in a string and separates the string into an array. Anything parameter in split() will be the separator so split(“”) would simply have no separator. Next, reverse() simply reverses an array so the first array element becomes the last and the last becomes the first. And finally, the join() method takes in an array and joins it into a string. Using all three in that exact will give you a working algorithm to this problem.

When I first gave this a shot many months ago, I coded everything without using built-in methods, but then I realized it would be cleaner and intuitive if I took it the easy way out.

That’s it for now, see you all next time!

 

Thomas Nguyen

 

Leave a Reply

Your email address will not be published. Required fields are marked *