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;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With