[Javascript] Replicate a string (code example)

Paul Novitski paul at novitskisoftware.com
Fri Jul 1 19:39:50 CDT 2005


That's interesting, Mike.  The logic looks like: for as many times as you 
can divide N by 2, double the string; each time, if the lowest bit of N is 
on, concatenate the cumulative string to the return value.

This routine, relying as it does on low-level binary logic, makes me 
nostalgic for the good old days of assembly language programming.  In a 
higher-level language it makes me nervous because it assumes that N is 
stored in memory as a pure binary value, but other than that it looks 
pretty elegant to me.

Paul


At 05:17 PM 7/1/2005, Mike Dougherty wrote:
>Someone was just asking in IRC how to replicate a string, which reminded 
>me of the following code example.  It uses bitwise operators to control 
>the iteration of multiple additions.  The code is unintuitive, but if you 
>examine it in a console you will see how efficient it is.  I thought I'd 
>share in case anyone else has a use for a REPLicate function.  ( I didn't 
>write it, but could not find this example using google either )
>
>/* REPLicate a string (s) some number of times (n) */
>function repl(s,n) {
>   var r='';
>   while(n) {
>     if(n&1) {r+=s;}
>     s+=s;
>     n>>=1;
>     }
>   return r;
>   }





More information about the Javascript mailing list