Tip? Short way to generate up to 12 repeated characters in JavaScript

8

'---------'
'-'.repeat(9) // longer!

'------------'
(x='----')+x+x
'-'.repeat(12) // same length

Is there any cleverer way of generating strings of up to 12 repeated characters in JavaScript?

Steve Bennett

Posted 2017-05-28T11:26:39.103

Reputation: 1 558

1Don't think so but depending on the challenge you may be able to golf multiple runs to save bytes using e.g. RLE – ASCII-only – 2017-05-28T11:46:35.127

9For the special case of commas you can do Array(12)+'', which is shorter than the literal starting at 11 commas and then remains shorter than repeat. – Martin Ender – 2017-05-28T11:51:24.873

Cool - how often do you need a string of commas? – Steve Bennett – 2017-05-28T12:07:53.380

1@SteveBennett sometimes you only care about the string length and not the actual character, and many PPCG challenges allow you to use some ASCII character of your choice for output. – Martin Ender – 2017-05-28T12:15:18.923

1If you're going to be reusing repeat, you can alias it. – Shaggy – 2017-05-28T12:15:31.633

5If you don't really need 12 identical characters but rather a 12-character string, you can also do 1e11+''. – Arnauld – 2017-05-28T12:47:10.417

I'm not sure about javascript, but in python you can do '-'*12 – FantaC – 2017-05-31T14:45:30.230

Yeah, that's awesome but doesn't work in JS. – Steve Bennett – 2017-06-01T00:02:26.400

Answers

2

Unfortunately, after what seems an eternity of searching documentation, I can't seem find any solution that will work with the 12-character constraint and generate for any given character given. However, there are a few neat tricks one can do to save some bytes for specific cases:

  • 1eL-1+'' will give a string, filled with 9s, of L length.
  • ''.padEnd(L) will give a string, filled with spaces, of L length. It's only useful when L > 10, otherwise it's too long. This one can be immediately chained with a function.
  • N/9+'' will give a string, starting with 0. then followed by a bunch of Ns. This does not work when N < 1 or N > 8, and the result obviously does not contain the same characters the whole way, but pretty close and pretty short.
  • Array(L)+'' will give a string, filled with commas, of length L - 1.

XavCo7

Posted 2017-05-28T11:26:39.103

Reputation: 274

1Along the lines of your 1/3+'' tip, you can repeat a digit D (except 0 and 9) a bunch of times similarly with D/9+''. – kamoroso94 – 2017-10-11T00:36:11.740

Array(L)+'' gives L-1 length, right? – Dom Hastings – 2017-10-11T05:49:58.517

Which means that for L=13, the code is 12 characters and the output is 12 characters, so the same as ','.repeat(12) – Steve Bennett – 2017-10-11T06:11:20.867