I'm doing char golfing these days in different languages and I was skeptic at first cause it's totally disconnected from 'real world' practices but I ended up loving it for its educationnal purpose: I learned a LOT about my languages in the process. And let's admit it, it's fun.
I'm currently trying to learn tricks in JS and here's the last I found:
Say, you have this script:
for(i=5;i--;)print(i*i) (23 chars)
The script is made of ASCII chars, each of them is basically a pair of hex digits. For example 'f' is 66 and 'o' is 6f. So if you group the informations of these two chars you get: 666f, which the utf16 code of one char: 景
My script has an odd number of chars so let's add a space somewhere to make it even:
for(i=5;i--;) print(i*i) (24 chars)
and now by applying the previous idea to the whole script we get:
景爨椽㔻椭ⴻ⤠灲楮琨椪椩 (12 chars)
So now my question is: how can I reconstruct the script back from the 12 chars with as few chars as possible?
I came up with that:
eval(unescape(escape`景爨椽㔻椭ⴻ⤠灲楮琨椪椩`.replace(/%u(..)/g,'%$1%')))
but it adds a constant cost of 50 chars to the process so it makes this method useless if your script has less than 100 chars. It's great for long scripts (e.g. 600 chars becomes 350 chars) but in golfing problems, the script is rarely long, usually it's less than 100 chars.
I'm not an encoding specialist at all, that's why I came here cause I'm pretty sure there's a shorter method. 30 chars of constant cost would be already amazing cause it would make the threshold drop from 100 to 60 chars. Note that I used utf16 here but it could be another encoding, as long as it shortens the script I'm happy with it. My Version of JS is: Node 12.13.0