Compressing Long Strings
If you have a very long, repetitive string, you can compress it using something similar to:
``.replace(/./gs,p=>p.charCodeAt().toString(2).padStart(7,0)).match(/.{n}/g).map(p=>+("0b"+p))
The ``
should contain any code points between 0 and 127, with some needing to be escaped. These are: 0x00
(\0
or \x00
, depending on whether a digit is following), 0x0d
(\r
), 0x5c
(\\
), and 0x60
(\`
). In some very rare cases you may need to escape a $
if it is followed by a {
.
You should replace n
with the number of bits the output should be grouped into, and you can put any code you want in the final map
and use +("0x"+p)
to get the decimal value wherever necessary.
This adds roughly 100 bytes of overhead, compared to atob
/btoa
's 8. This method fits just under 7 bits per character in the string (due to escaping), and takes advantage of the fact that JS lets you put pretty much any code points into a string.
In order for this to be shorter, the data compressed needs to be one of:
- Binary or numeric data, which is difficult to work with using
atob
and btoa
- A string that has few distinct characters and is longer than 100 or so characters
In order to create a compressed string, convert each chunk of the string to binary using whatever encoding you want, then break it into chunks 7 bits wide. You may need to add some padding, which will be ignored if it is under 7 bits. Then, convert these into code points and paste them into the string.
var
)? And should JavaScript golf code be a function or output something directly? I honestly think this can make much difference. \$\endgroup\$(class{static #x = 1;get #y(){};set #y(z){}})
can be rewritten as(class{static#x = 1;get#y(){};set#y(z){}})
. This makes for some nice obfuscation, too, but I can’t think of a practical example in code golf. \$\endgroup\$