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

Reversed Strings (8kyu) [TypeScript]


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.

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

export function solution(str: string): string {
    let answer: string[] = []
    for(let i = 0; i < str.length; i++) {
        const char = str[i]
        answer.unshift(char)
    }
    console.log(answer)
    return answer.join('')
}

Solution 2

Let's solve it with reverse & join.

export function solution(str: string): string {
    return str.split("").reverse().join("")
}

Solution 3

Let's solve it with reduce.

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

Solution 4

Let's solve it with map.

export function solution(str: string): string {
    return str.split("").map((char, index, arr) => arr[arr.length - index - 1]).join("")
}

Solution 5

Let's solve it with recursion.

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