andré nanninga

Train Ride

JS1k is a code golfing competition challenging programmers to create a neat little JavaScript program in under 1024 bytes. This years theme was Hype Train.

I found out about this competition in March and thought that could make for a nice little side project. I didn’t have any particular idea of what to make but I knew that I wanted to make something that had a nice look to it, something that looked polished.

Fairly quickly I had something that looked like the above demo but that exceeded the limit of 1024 bytes by quite a bit. I started at first by using single letter variables and making short references to often used function. For example canvas.moveTo became c.m. This made a little dent in the size but turned out to be not that helpful later1. Using the obvious solution of uglify-js was a much bigger help in reducing the file size.

However the biggest gain was found by looking at the techniques used by other entries in the older competitions. RegPack is a library that turns the code intro a string and replaces commonly used substrings within the code with a regex match. During runtime the regex is used to restore the original string which is then run using eval(). Try the demo to see it in action.

RegPack shaved about 200 bytes of my minified code and proved to be invaluable.

[1] RegPack replaces commonly used substrings with regex. While I haven’t actually tested it I suspect it would do a better job at shortening the final code than I did.

Train Ride

Finally i submitted a program simply called Train Ride. The code and supporting libraries can be found in this GitHub repo. The fully minified code that was submitted for judgement in the competition looked like this:

0==S=i*MMath.b(FSGf&&(,y=-i*IStyle=(e%O*m[l]":-unction20;"rg"+( %150==+VE+Ni-1,for(L,"+
(strokefillf Nc,l){return =||randomc||1==c?-8:l6||l7?0:8*siNc-9*)}d=e=t=64,M=32,I=
1MI++OM+O-38*T-MI)G()6A3331==iAb52i<3&&J-1A953T? 76-h+2*P1H-3*h30-h-iL) 113-h+3*PH1-
';g=/[^ -?CIMPSTW[-~]/.exec(_);)with(_.split(g))_=join(shift());eval(_)

Train Ride on