10 8 1 1 the reverse function

Solutions on MaxInterview for 10 8 1 1 the reverse function by the best coders in the world

showing results for - "10 8 1 1 the reverse function"
Vasco
22 Jan 2017
1//Let's write a function that, given a string, returns its reverse.
2
3//One approach uses the accumulator pattern:
4
5function reverse(str) {
6   let reversed = '';
7
8   for (let i = 0; i < str.length; i++) {
9      reversed = str[i] + reversed;
10   }
11
12   return reversed;
13}
14
15/*This is the same algorithm that we used previously to reverse a string.
16
17Another approach is to use the fact that there is a reverse method for 
18arrays, and that the methods split and join allow us to go from strings 
19to arrays and back (this was covered in Array Methods).*/
20
21function reverse(str) {
22   let lettersArray = str.split('');
23   let reversedLettersArray = lettersArray.reverse();
24   return reversedLettersArray.join('');
25}