2

I have a char ('-') and a number (80) of times it should be repeated in a string. I need to get a string of that char repeated given number of times:

-------------------------------------------------------------------------------------------------------------

I know I can do result += myChar x N times in a loop. I don't think it is very efficient. Is there a better way to do that?

By the most efficient I mean: fastest

Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159
  • Take a look here: http://jsperf.com/zerofill-any and replace "0" with your character. – kalley Aug 12 '13 at 21:11
  • 4
    You an do `(new Array(81)).join('-')` if you want something short that doesn't explicitly code a loop. (But I would assume `.join()` is implemented with a loop.) You can test the performance versus a loop for yourself at http://jsperf.com. – nnnnnn Aug 12 '13 at 21:11
  • @nnnnnn the binary tree method is good, but if an upper limit to the length is known, you can just store a global string of 80 dashes and take substrings. You won't get faster than that. Similarly, a function which generates the string could cache the resulting string and only generate further when needed. – Dave Aug 12 '13 at 21:15
  • sorry that should have been @kalley – Dave Aug 12 '13 at 21:15
  • 1
    Best way to do something is not a good fit for SO... – Ruan Mendes Aug 12 '13 at 21:20
  • 1
    @kalley I had a go at implementing my optimisation on that page. It's much faster when the length is sufficient that caching matters (I tried 30), but slower otherwise (as you'd expect) http://jsperf.com/zerofill-any/2 – Dave Aug 12 '13 at 21:37
  • @bonomo Because questions about the best way "[...] will likely solicit debate, arguments, polling, or extended discussion." See http://stackoverflow.com/help/dont-ask Make your question specific about what aspect you actually would like to improve. Otherwise it's too open ended and a better fit for http://codereview.stackexchange.com – Ruan Mendes Aug 12 '13 at 23:53

1 Answers1

2

Well, the best I could come up with, after a couple minutes playing, is:

String.prototype.repeat = function (len) {
    return (new Array(len + 1)).join(this);
}

console.log('-'.repeat(5));

JS Fiddle demo.

Which is, unfortunately, cheapened a little as @nnnnnn commented with the correct answer two minutes beforehand. Sigh...

Community
  • 1
  • 1
David Thomas
  • 249,100
  • 51
  • 377
  • 410