Home > katas > String repeat (8kyu) [TypeScript]

String repeat (8kyu) [TypeScript]


Chek kata on Codewars

Description:

Write a function called repeat_str which repeats the given string src exactly count times.

repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"

Solution 1.1

Let's start with a loop solution.

export function repeatStr(n: number, s: String): String  {
    let newString: String = ''
    while (n > 0) {
        newString = `${newString}${s}`
        n--
    }
    return newString
}

Solution 1.1 +

Let's make it shorter.

export function repeatStr(n: number, s: String): String {
    let newString: String = ''
    while (n-- > 0) newString = `${newString}${s}`
    return newString
}

Solution 1.2

export function repeatStr(n: number, s: String): String  {
    let newString: String = ''
    for (let i = 0; i < n; i++) {
        newString = `${newString}${s}`
    }
    return newString
}

Solution 1.3

We can add an array to this for loop.

export function repeatStr(n: number, s: String): String  {
    let newString: String[]  = []
    for (let i = 0; i < n; i++) {
        newString.push(s)
    }
    return newString.join('')
}

Solution 2.1

If you wonder whether there is a built-in method. The answer is yes. The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

export const repeatStr = (n: number, s: String): String => s.repeat(n)

Solution 2.2

Or we can dynamically call it.

export const repeatStr = (n: number, s: String): String => s["repeat"](n);

Solution 3.1

Using the apply() method with the Array constructor function.

export function repeatStr(n: number, s: string): string {
    return Array.apply(null, Array(n)).map((i) => s).join('')
}
© 2021, Andrew Losseff