0

I was doing a question on Javascript where I had to append dashes N times. Naturally I ran a for loop.

for (var i=0; i<num; i++)
{
newStr+="-";
}

But then I realise that I could cut the runtime in half if I append two dashes in one loop.

for (var i=0; i<num/2; i++)
{
newStr+="--"
}
if (num%2==1)
{
newStr+=1;
}

So if I append three dashes in one loop I could cut in in 1/3 of the time taken?

But appending too much will somehow make it back to square one.

What is the fastest/most optimal way to do this?

1 Answers1

3

You might use String.prototype.repeat:

newStr += '-'.repeat(num)

let newStr = 'foo';
const num = 5;
newStr += '-'.repeat(num)
console.log(newStr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320