Last active
August 29, 2015 14:01
-
-
Save mindoftea/bfc61e82c546b63005c3 to your computer and use it in GitHub Desktop.
A fast homogenous JavaScript array generator. Given some string, it generates an array of arbitrary length containing that string repeated. It uses binary concatenation and string addition to achieve its speed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var generateArray=function(x,n) | |
{ | |
var s,y,z; | |
s=""; | |
if(x.length>1) | |
{ | |
s="|"; | |
} | |
x+=s; | |
y=""; | |
while(n>0) | |
{ | |
if(n%2) | |
{ | |
y+=x; | |
n--; | |
} | |
if(n!==0) | |
{ | |
x+=x; | |
n/=2; | |
} | |
} | |
y=y.split(s); | |
y.pop(); | |
return y; | |
}; | |
generateArray("abc",5); | |
// returns ["abc","abc","abc","abc","abc"]. | |
generateArray("x",1594323); | |
// Takes just 75ms. | |
generateArray("xyz",1594323); | |
// Takes just 185ms. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment