Home > katas > Reversed Strings (8kyu) [JavaScript]

Reversed Strings (8kyu) [JavaScript]


Chek kata on Codewars

Description:

Complete the solution so that it reverses the string passed into it.

'world'  =>  'dlrow'

Solution 1

Let's start with loop solutions.

function solution(str) {
    let newStr = ""
    for(let i = str.length - 1; i >= 0; i--) {
        newStr +=str[i]
    }
    return newStr
}

function solution(str) {
    let answer = []
    for(let i = 0; i < str.length; i++) {
        answer.unshift(str[i])
    }
    return answer.join('')
}

Solution 2

Let's solve it with reverse & join.

function solution(str){
  return str.split('').reverse().join('');
}

function solution(str){
  return [...str].reverse().join("")
}

Solution 3

Let's solve it with reduce.

function solution(str) {
    return str.split("").reduceRight((acc, cur) => acc + cur)
}

Solution 4

Let's solve it with map.

function solution(str) {
    return [...str].map((character, index, arr) => arr[arr.length-index-1]).join("")
}

Solution 5

Let's solve it with recursion.

function solution(str){
    return str.length > 0 ? solution(str.substring(1)) + str.charAt(0) : '';
}
© 2021, Andrew Losseff