String Reversal v4

String Reversal v4

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

Example:
reverse(‘apple’) = ‘leppa’
reverse(‘hello’) = ‘olleh’
reverse(‘Greetings’) = ‘sgniteerG’

function reverse(str) {
 return str.split('').reduce((character, reversed) => {
    return character + reversed
  }, '')
}

console.log(reverse('apple')) => 'leppa'

We create a function in our case called reverse with a parameter I choose str

Then we are going to return str parameter and use split method to turn the string into an array like str.split(‘’)

Then we are going to chain reduce method that takes two arguments one callback function and second one starting initial value for our function which I’m going to pass in an empty string

This reduce function will run for one time for every element whitin the array so we can picture that this first value for the first argument that has passed in reduce is reduce string named reversed

And the second argument is the element of the character that we are currently operating on out of our array and we will call this second argument character

The logic inside this function will be that we will take our character that we are operating right now we will add it to the total reverse string or the strng that represents the reversed string that we were past and then return the result.
return character + reversed

comments powered by Disqus