Following on from Axel's mind blowing string repeat function, I decided to see if I could use recursion to implement the same functionality.

Turned out to be quite easy. I did it with TDD, while remaining faithful to Axel's implementation. I've pushed the code to github under connrs/recursive-string-repeat but I will replicate the function here:

function repeat(num, str) {
    num = Number(num);

    if (num === 0) {
        return '';
    }

    return repeat(num >>> 1, str + str) + (num & 1 ? str : '');
}

I know that JS perf testing isn't really important for something like this, but I wanted to do it as part of the experiment. Here are the test results compared to Axel's version. Looks like for loops win!

I must admit that it was quite fun to try this out.

Comments

When you register to leave a comment, no personal information, other than the name that you provide, will be displayed to visitors of the site.

You may use Markdown to enhance your comments but please note that all comments are moderated before being published and I reserve the right to amend any comment to make it more suitable for layout or to remove any inappropriate language.

You must sign in to leave a comment

Posted by connrs on :

test