I wrote a .repeat(n) function for strings which seemed to work fine:
String.prototyp e.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 8 1923
Csaba Gabor wrote: I wrote a .repeat(n) function for strings which seemed to work fine:
String.prototyp e.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.
"Csaba Gabor" <da*****@gmail. com> writes: I wrote a .repeat(n) function for strings which seemed to work fine:
String.prototyp e.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
(stringExpressi on).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.prototyp e.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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Richard Cornford wrote: Csaba Gabor wrote: I wrote a .repeat(n) function for strings which seemed to work fine:
String.prototyp e.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.
Csaba Gabor wrote: I wrote a .repeat(n) function for strings which seemed to work fine:
String.prototyp e.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).
"VK" <sc**********@y ahoo.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.prototyp e 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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
JRS: In article <11************ **********@e56g 2000cwe.googleg roups.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.prototy pe.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.prototyp e.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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Dr John Stockton wrote: JRS: In article <11************ **********@e56g 2000cwe.googleg roups.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.prototy pe.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.prototyp e.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.
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Brad Tilley |
last post by:
Is there an easier way to do this:
def print_whats_returned(function):
print function
print type(function)
|
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 on CSAPI_V2 to scott;
When I attach to the database in C# using ODP.NET and attempt to
|
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",
"getSetupByDescription", parameter);
setup = (Transaction.SetupInfo)objTem;
|
by: Juan |
last post by:
how to get number of rows returned by a SqlDataReader without having to
scroll it?
|
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 method? Second, how do I do it? I know how
to write the method, pass arguments to it and get a single value returned
but how do I pass multiple values back? Last, how do I reference the various
values returned? I assume there is some array used...
| |
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",
"Password"
objXMLHTTPServer.setRequestHeader "Content-Type",
"application/x-www-form-urlencoded"
....
|
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 *pFile;
char *cFileName;
cFileName=argv;
pFile = fopen(cFileName,"a+");
cFileName has a valid filename ('apm.dbg'), and I have full write
|
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 registered on the system. How can I
determine which type is returned.
I tried if (objWebRequest is System.Net.HttpWebRequest) then .....
But the system says I am not allowed to use types in expressions.
--
|
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. found out there is no boolean
type in Oracle parameter in OracleType. How can I get the returned value from
function call in my code?
Thanks in advance
|
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 as an XML response.
My question is: Is there way to get the data that is returned in the response so I can use that data on my website. I tried talking to them but they don't have any tech people there. Plus I would rather the response didn't show...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |