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

String repeat (8kyu) [JavaScript]


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.

function repeatStr (n, s) {
    let newString = ''
    while(n > 0) {
        newString += s
        n--
    }
    return newString
}

Solution 1.1 +

Let's make it shorter.

function repeatStr (n, s) {
    let newString = ''
    while(n-- > 0) newString += s
    return newString
}

Solution 1.2

function repeatStr (n, s) {
    let newString = ''
    for(let i = 0; i < n; i++) {
        newString += s
    }
    return newString
}

Solution 1.3

We can add an array to this for loop.

function repeatStr (n, s) {
    let newString = []
    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.

const repeatStr = (n, s) => s.repeat(n)

Solution 2.2

Or we can dynamically call it.

const repeatStr = (n, s) => s["repeat"](n)

Solution 3.1

Let's solve it recursively.

function repeatStr (n, s) {
  return n > 1 ? s + repeatStr(--n, s) : s;
}

Solution 4.1

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

const repeatStr = (n, s) => {
    return Array.apply(null, Array(n)).map((i) => s).join('')
}

Solution 4.2

Let's simplify it.

function repeatStr (n, s) {
  return Array(n+1).join(s);
}

Solution 4.3

Or we can use .fill() method, which changes all elements in an array to given value.

function repeatStr (n, s) {
  return new Array(n).fill(s).join('');
}

Solution 5.1

Using Array.from() + reducer The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.

function repeatStr (n, s) {
    return Array.from(Array(n)).reduce(acc => acc + s, '')
}
© 2021, Andrew Losseff