Answers for "10.8.1.1. The reverse Function"

0

10.8.1.1. The reverse Function

//Let's write a function that, given a string, returns its reverse.

//One approach uses the accumulator pattern:

function reverse(str) {
   let reversed = '';

   for (let i = 0; i < str.length; i++) {
      reversed = str[i] + reversed;
   }

   return reversed;
}

/*This is the same algorithm that we used previously to reverse a string.

Another approach is to use the fact that there is a reverse method for 
arrays, and that the methods split and join allow us to go from strings 
to arrays and back (this was covered in Array Methods).*/

function reverse(str) {
   let lettersArray = str.split('');
   let reversedLettersArray = lettersArray.reverse();
   return reversedLettersArray.join('');
}
Posted by: Guest on July-01-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language