Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create string of Letter and length of a string

I would like to create a string, from a letter and length of a string. This is what I currently have, but is there a better way to do this?

function generate(letter, len) {
   var str = '';
   for (var i=0; i<len; i++) {
     str+=letter;
   }
  
   return str;
  
}
like image 553
puppeteer701 Avatar asked Nov 20 '25 22:11

puppeteer701


1 Answers

Don't know if this is better in terms of performance as some engines optimize the code while others do not. However it's readable, to a javascript programmer.

You can create an array with size len + 1 and then join it by the letter.

For this, we will make use of array constructor, where we can define the size of the array and Array.join to join the array with the given letter.

function generate(letter, len) {
    return new Array(len + 1).join(letter); 
}
like image 119
Amit Joki Avatar answered Nov 22 '25 13:11

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!