3

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;
  
}

2
  • 1
    I think questions like this belongs on codereview.stackexchange.com Commented Jun 3, 2015 at 13:46
  • Depends on the js environment (ES6 String.prototype.repeat), available libraries in the environment, what you mean by "better" Commented Jun 3, 2015 at 14:08

1 Answer 1

4

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); 
}
Sign up to request clarification or add additional context in comments.

7 Comments

Why is this better? Is it faster? I doubt it. Is is easier to read? That can be discussed to infinity.
I think it's not better way to join probabily inifinite length of string. by creating array You're creating an object in ram, then You're joining it also consuming resources. Using "for loop" for generating is still better way.
@AmitJoki You don't know how the engine ( compiler / interpreter ) will handle sting concatenation. Maybe it will use something like the StringBuilder from Java or C#. Maybe it will reserve memory for each string and free it again after it's done being used.
Maybe it will inspect the code and make a string of length len and simply rewrite the concatenation to str[i] = letter.
@dev-null jsperf.com/for-vs-array-join/3 For loop may be faster when the len is small..but what happens when it becomes somewhat big? Talk about micro-optimization
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.