Address: http://www.davidflanagan.com/2009/08/string-multipli.html
Original Author: David Flanagan
In Ruby, the "*" operator uses a string as the left parameter and a number as the right parameter to implement string duplication. For example, the value of "Ruby" * 2 is "RubyRuby ". This is useful only in a few places (for example, generating a table consisting of ASCII characters such as hyphens), but it is very concise. It is much less efficient than writing a loop to connect strings for n times.
I just found that there is a clever technique in JavaScript to implement string multiplication:
Copy codeThe Code is as follows:
String. prototype. times = function (n ){
Return Array. prototype. join. call ({length: n + 1}, this );
};
"Js". times (5) // => "jsjsjsjsjs"
This method calls an Array. join () action of an Array whose elements are all "undefined. However, it does not actually create an array containing n + 1 "undefined" elements. It uses an anonymous object that contains the length attribute and relies on the original function join () of the Array object (). Because "Object" is not an array and cannot directly call join (), it must be implemented through the call () of the prototype. A simple version with the same effect is provided below:
Copy codeThe Code is as follows:
String. prototype. times = function (n) {return (new Array (n + 1). join (this );};
When we call the constructor with a parameter of Array, we only set the length of the Array. In fact, no elements of the Array are created.
I only tested it in Firefox. I guess it will be more effective than a normal loop, But I didn't perform a benchmark test.
Author Profile
David Flanagan is a computer programmer fascinated by Java writing. He spent most of his time writing Java-related books. David earned a computer science degree in engineering at the Massachusetts Institute of Technology. He lives on the Pacific Northwest Coast between Seattle and Vancouver. He published best-selling books in o'reilly, including Java in a Nutshell, Java Foundation Classes in a Nutshell, Java Enterprise in a Nutshell, and JavaScript: the Definitive Guide, JavaScript Pocket Reference, and The Ruby Programming Language.
My comments
If efficiency is to be considered, it may be more efficient to slightly optimize loop iterations. For example, in the following recursive call, the algorithm complexity is O (log2n ). In Google Chrome, the test result is faster than that of David, but I have to admit that his method is elegant!
Copy codeThe Code is as follows:
String. prototype. times = function (n ){
If (n = 1 ){
Return this;
}
Var midRes = this. times (Math. floor (n/2 ));
MidRes + = midRes;
If (n % 2 ){
MidRes + = this;
}
Return midRes;
}
Postscript
David adopted my suggestion and wrote a non-recursive version for us. See his blog article: http://www.davidflanagan.com/2009/08/good-algorithms.html.
Contact info
My mailbox, welcome letter (redraiment@gmail.com)