Skip to content

Instantly share code, notes, and snippets.

@mindoftea
Last active August 29, 2015 14:01
Show Gist options
  • Save mindoftea/bfc61e82c546b63005c3 to your computer and use it in GitHub Desktop.
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.
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