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
I've tested the performance of all the proposed approaches.
Here is the fastest variant I've got.
String.prototype.repeat = function(count) {
if (count < 1) return '';
var result = '', pattern = this.valueOf();
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
Or as stand-alone function:
function repeat(pattern, count) {
if (count < 1) return '';
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
}
It is based on artistoex algorithm.
It is really fast. And the bigger the count, the faster it goes compared with the traditional new Array(count + 1).join(string) approach.
I've only changed 2 things:
pattern = this with pattern = this.valueOf() (clears one obvious type conversion);if (count < 1) check from prototypejs to the top of function to exclude unnecessary actions in that case.UPD
Created a little performance-testing playground here for those who interested.
variable count ~ 0 .. 100:
constant count = 1024:
Use it and make it even faster if you can :)