Repeat String - Javascript

前端 未结 30 2415
长情又很酷
长情又很酷 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:56

    Simple recursive concatenation

    I just wanted to give it a bash, and made this:

    function ditto( s, r, c ) {
        return c-- ? ditto( s, r += s, c ) : r;
    }
    
    ditto( "foo", "", 128 );
    

    I can't say I gave it much thought, and it probably shows :-)

    This is arguably better

    String.prototype.ditto = function( c ) {
        return --c ? this + this.ditto( c ) : this;
    };
    
    "foo".ditto( 128 );
    

    And it's a lot like an answer already posted - I know this.

    But why be recursive at all?

    And how about a little default behaviour too?

    String.prototype.ditto = function() {
        var c = Number( arguments[ 0 ] ) || 2,
            r = this.valueOf();
        while ( --c ) {
            r += this;
        }
        return r;
    }
    
    "foo".ditto();
    

    Because, although the non recursive method will handle arbitrarily large repeats without hitting call stack limits, it's a lot slower.

    Why did I bother adding more methods that aren't half as clever as those already posted?

    Partly for my own amusement, and partly to point out in the simplest way I know that there are many ways to skin a cat, and depending on the situation, it's quite possible that the apparently best method isn't ideal.

    A relatively fast and sophisticated method may effectively crash and burn under certain circumstances, whilst a slower, simpler method may get the job done - eventually.

    Some methods may be little more than exploits, and as such prone to being fixed out of existence, and other methods may work beautifully in all conditions, but are so constructed that one simply has no idea how it works.

    "So what if I dunno how it works?!"

    Seriously?

    JavaScript suffers from one of its greatest strengths; it's highly tolerant of bad behaviour, and so flexible it'll bend over backwards to return results, when it might have been better for everyone if it'd snapped!

    "With great power, comes great responsibility" ;-)

    But more seriously and importantly, although general questions like this do lead to awesomeness in the form of clever answers that if nothing else, expand one's knowledge and horizons, in the end, the task at hand - the practical script that uses the resulting method - may require a little less, or a little more clever than is suggested.

    These "perfect" algorithms are fun and all, but "one size fits all" will rarely if ever be better than tailor made.

    This sermon was brought to you courtesy of a lack of sleep and a passing interest. Go forth and code!

提交回复
热议问题