"Csaba Gabor" <da*****@gmail.com> writes:
I wrote a .repeat(n) function for strings which seemed to work fine:
String.prototype.repeat = function(n) {
// repeats the string n times
if (n<1) return "";
if (n<2) return this;
.... Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));
It's not so surpricing. The "this" operator always refer to an object,
and that is what you return.
When you write
(stringExpression).methodCall()
(e.g. "foo".repeat(1)), the string value (a primitive type) is promoted
to an object as if by (new String("foo")) and the method is called on
that object. That's why you are allowed method calls on primitive values
at all.
What you can do is:
if (n < 2) { return this.toString(); }
which is equivalent to what you are doing except that it saves the
empty concatenation (but costs a method call).
Likewise, for a slight bit of efficiency (as if it mattered), the
loop could be:
for (var aStr = [this.toString()];--n>0;) aStr.push(this.toString());
(or better:
var s = this.toString();
for (var aStr = [s];--n>0;) aStr.push(s);
for large n's it saves n calls to toString)
I wouldn't worry about performance in the trivial cases, as they won't
take long anyway, and just do the more readable:
String.prototype.repeat = function repeate(n) {
var rep = [];
var s = this.toString(); // care a little about performance for the big n's
while(n > 0) {
rep.push(s);
n--;
}
return rep.join("");
}
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'