Exercise 1: String Reversal

Directions

Given a string, return a new string with the reversed order of characters

Examples

reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'

Guidelines

Three possible solutions:

  1. Use multiple string library functions
  2. Use for...of loop
  3. Use array helper reduce

Solution

In [4]:
function reverse(str) {
  return str.split("").reverse().join("");
}

Alernative Solution: for...of loop

In [2]:
function reverse(str) {
  let reversed = "";
  for (let character of str){ /* try not to use for loop, use for...of loop instead! */
    reversed = character + reversed;
  }
  return reversed;
}

Alernative Solution: reduce()

In [3]:
function reverse(str){
  return str.split("").reduce((rev, char) =>
    char + rev
  ,"");
}
In [5]:
reverse('apple')
Out[5]:
'elppa'
In [6]:
reverse('hello')
Out[6]:
'olleh'
In [7]:
reverse('Greetings!')
Out[7]:
'!sgniteerG'