473,386 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

returned type of -this- from String.prototype.repeat()

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;
for (var aStr = [this];--n>0;) aStr.push(aStr[0]);
return aStr.join("");
}

Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));

I fixed this by modifying ...
if (n<2) return this+"";

Just something I thought I'd share,
Csaba Gabor from Vienna

May 10 '06 #1
8 1900

Csaba Gabor wrote:
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;
for (var aStr = [this];--n>0;) aStr.push(aStr[0]);
return aStr.join("");
}

Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));

I fixed this by modifying ...
if (n<2) return this+"";
Maybe alos:-

return this.toString();

or

return String(this);

Just something I thought I'd share,


OK. But why were you surprised? the - this - keyword _always_ refers to
an object.

Richard.

May 10 '06 #2
"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.'
May 10 '06 #3
Richard Cornford wrote:
Csaba Gabor wrote:
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;
for (var aStr = [this];--n>0;) aStr.push(aStr[0]);
return aStr.join("");
}

Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));

I fixed this by modifying ...
if (n<2) return this+"";


Maybe alos:-

return this.toString();

or

return String(this);
Just something I thought I'd share,


OK. But why were you surprised? the - this - keyword _always_ refers to
an object.


Right after posting, I went running from the Opera to the Schloss
Schonbrunn and back, and with the delightful weather, there are patches
of swarming midge's and my eye chanced to run into one, capturing it
under my lower eyelid, which I could only extricate upon return. As if
I didn't have enough bugs to deal with.

Thanks for the speedy reply. The answer to your question is: In four+
years of javascript coding, this is the first time (I remember seeing)
that the distinction between string vs. object actually makes a
difference. I mean, I have read this distinction between strings and
objects (but never with examples), and when something walks like a
duck, and quacks like a duck for long enough, one tends to forget that
it still might not be a duck under the covers. Javascript has taken
care of the details so well, that in my mind a string has become a
special object, sort of like a function is.

May 10 '06 #4
VK

Csaba Gabor wrote:
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;
for (var aStr = [this];--n>0;) aStr.push(aStr[0]);
return aStr.join("");
}

Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));

I fixed this by modifying ...
if (n<2) return this+"";

Just something I thought I'd share,


return (aStr.join("")).toString();
would do the trick too (to cast a String object back to primitive),
unless you have overloaded toString method for other needs.

In JScript you also could do
return (aStr.join("")).valueOf();
but I'm not sure if it's supported in the standard JavaScript (out of
my test pages right now).

May 10 '06 #5
"VK" <sc**********@yahoo.com> writes:
return (aStr.join("")).toString();
would do the trick too (to cast a String object back to primitive),
Not necessary. The join method always returns a primitive string
value. The join operation will convert each element in the array to a
primitive string during the operation, if they aren't already.

You will just wrap the string value in a new String object for calling
the toString method.

The problem the original poster experienced was only in the n<2 case
where the value of "this" was returned.
unless you have overloaded toString method for other needs.

In JScript you also could do
return (aStr.join("")).valueOf();
Same thing. The valueOf method on String.prototype is equivalent to
the toString method. Both return the primitive string value contained
in the object.
but I'm not sure if it's supported in the standard JavaScript (out of
my test pages right now).


It's ECMAScript compliant.

/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.'
May 10 '06 #6
JRS: In article <11**********************@e56g2000cwe.googlegroups .com>
, dated Tue, 9 May 2006 08:35:34 remote, seen in
news:comp.lang.javascript, Csaba Gabor <da*****@gmail.com> posted :
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;
for (var aStr = [this];--n>0;) aStr.push(aStr[0]);
return aStr.join("");
}

Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));

I fixed this by modifying ...
if (n<2) return this+"";


ISTM that you can also fix it by removing that line.

Try

String.prototype.repeat = function(n) {
// repeats the string n times
for (var aStr = [] ; n-- > 0;) aStr[aStr.length] = this ; // or push
return aStr.join("") }

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
May 10 '06 #7
Dr John Stockton wrote:
JRS: In article <11**********************@e56g2000cwe.googlegroups .com>
, dated Tue, 9 May 2006 08:35:34 remote, seen in
news:comp.lang.javascript, Csaba Gabor <da*****@gmail.com> posted :
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;
for (var aStr = [this];--n>0;) aStr.push(aStr[0]);
return aStr.join("");
}

Only I was a little surprised to get "object" (instead of "string")
when I tried:
alert (typeof ("x".repeat(1)));

I fixed this by modifying ...
if (n<2) return this+"";


ISTM that you can also fix it by removing that line.

Try

String.prototype.repeat = function(n) {
// repeats the string n times
for (var aStr = [] ; n-- > 0;) aStr[aStr.length] = this ; // or push
return aStr.join("") }


which is exactly what Lasse proposed at the end of his initial response
(only his solution is more efficient because he sets var
s=this.toString() (and by the way, is there any difference in
efficiency between that and var s=String(this); ?)

What you've shown is how my function started out. I'm using it in key
event handlers which can potentially involve replacement of many KBs of
text in textareas (to compensate for some FF bugs). And then I
thought, "Hold the phone... in the vast majority of cases, I'm going to
be calling this with n=1 so why should I be making extra copies of this
string?" And that's what led to the special cases.

May 10 '06 #8
Csaba Gabor wrote :
<snip>
... (and by the way, is there any difference in
efficiency between that and var s=String(this); ?)

<snip>

It is probably less efficient as the - String - constructor called as a
function with an object argument implicitly calls the object's -
toString - method, implying the additional overhead of the - String -
function call. Implementation's may optimise this out, but also may not.

Richard.
May 10 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Brad Tilley | last post by:
Is there an easier way to do this: def print_whats_returned(function): print function print type(function)
6
by: Matthew Houseman | last post by:
All, I've created a synonym that points to a package over a database link like so: CREATE SYNONYM API_MYLINK FOR USER.CSAPI_V2@INSTANCE.DOMAIN.COM I've granted execute like so: grant execute...
0
by: David | last post by:
Hi, I have a program in which I used invokemember to late bind to a component. In my code I use: SetupInfo setup; Object objTem = callLateBinding ("BackOfficeServer.BackOffice",...
3
by: Juan | last post by:
how to get number of rows returned by a SqlDataReader without having to scroll it?
5
by: Homer Simpson | last post by:
Hi All, I'm trying to write a method where I pass three arguments and the method returns six values. All the values will be doubles. First, is it possible to get multiple values returned by a...
2
by: edsuslen | last post by:
I am migrating working code (HTTPRequest with Authentication) from vb to vb.net vb: Set objXMLHTTPServer = New MSXML2.XMLHTTP30 objXMLHTTPServer.Open strMethod, strGetRequest, False, "UserId",...
39
by: ferrad | last post by:
I am trying to open a file for appending. ie. if the file exists, open it for appending, if not, create it. I am getting back a NULL pointer, and do not know why. Here is my code: FILE...
2
by: Johannes | last post by:
When you do a webrequest like: Dim objWebRequest As WebRequest = WebRequest.Create(objURI) the returned class can be httpwebrequest, ftpwebrequest or any othe descendant webrequest type that is...
2
by: John | last post by:
My application needs to call Oracle function using oracle client 9.2. The oracle function returns boolean value from its returned parameter. The name space that I used is system.data.oracleclient....
6
by: dboyerco | last post by:
I'm working with a company that is tracking my vihicle and they have an API that will allow me to log into their database and retrieve the location of my vihicle, which is returned to their website...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.