Repeat String - Javascript

前端 未结 30 2219
长情又很酷
长情又很酷 2020-11-22 08:46

What is the best or most concise method for returning a string repeated an arbitrary amount of times?

The following is my best shot so far:

function          


        
30条回答
  •  一个人的身影
    2020-11-22 08:57

    Firstly, the OP's questions seems to be about conciseness - which I understand to mean "simple and easy to read", while most answers seem to be about efficiency - which is obviously not the same thing and also I think that unless you implement some very specific large data manipulating algorithms, shouldn't worry you when you come to implement basic data manipulation Javascript functions. Conciseness is much more important.

    Secondly, as André Laszlo noted, String.repeat is part of ECMAScript 6 and already available in several popular implementations - so the most concise implementation of String.repeat is not to implement it ;-)

    Lastly, if you need to support hosts that don't offer the ECMAScript 6 implementation, MDN's polyfill mentioned by André Laszlo is anything but concise.

    So, without further ado - here is my concise polyfill:

    String.prototype.repeat = String.prototype.repeat || function(n){
        return n<=1 ? this : this.concat(this.repeat(n-1));
    }
    

    Yes, this is a recursion. I like recursions - they are simple and if done correctly are easy to understand. Regarding efficiency, if the language supports it they can be very efficient if written correctly.

    From my tests, this method is ~60% faster than the Array.join approach. Although it obviously comes nowhere close disfated's implementation, it is much simpler than both.

    My test setup is node v0.10, using "Strict mode" (I think it enables some sort of TCO), calling repeat(1000) on a 10 character string a million times.

提交回复
热议问题