Veka0881
Veka0881

Reputation: 170

javascript exercise - recursive function with a string

console.log( ‘blah’.repeatMe( 3 ) );

Using Javascript write the code that would make the previous function print:

Output: blahblahblah

Upvotes: 0

Views: 203

Answers (1)

Lye Fish
Lye Fish

Reputation: 2578

Oh, it's too fun to pass up a functional style solution.

String.prototype.repeatMe = function(n) {
    if (n <= 0) return "";
    if (n%2 === 1) return (""+this) + this.repeatMe(n-1);

    var half = this.repeatMe(n/2);
    return half + half;
}

document.body.innerHTML = "tester".repeat(10)

I'll let you work out what's happening as an exercise.

Upvotes: 1

Related Questions