JavaScript ‘Microfication’

After I finished Wavy Waves, some work was left to do to reduce its size, fitting into JS1K contest’s 1024 bytes limit. To achieve this incredible size I used Google’s Closure Compiller and the code got reduced drastically to 818 bytes, that means more of 50% of size reduction.

The script generated by Closure Compiler is a little bit ugly and hard to read, but here it is:

But for me, 818 bytes were not enough. I just *needed* to reduce more! After getting some inspiration on Peter’s minification article I started to do the procedure described below.

First lets have a look in the indented code to understand it:

This code have some points to optimize. For instance the code that makes the particle wrap have a sequence of conditions to test it and it is a little bit long. To make it to wrap on the higher value, it is easy, just use the modulus:

But to do it on the lower side I cannot do just a %, I need to translate the point, summing the width. So the sequence of if/elses can be replaced by:

And I can update the velocity values when I’m doing the math!! Transforming the old code:

Into:

Ok, half of the update code is solved with with those two lines. Inside the update/draw step, a reference for the var a is used 20 times after the optimization above, so 40 chars (20 x a.) are used to manipulate the data. Using the with statement could give us a help.

Here is our code to apply the new statement:

After the with we get raid of 34 bytes (considering the a initialization + all its references – with(){}):

Now, the speed control functions initialization are minified, but they aren’t at the best way. Lets revise the code:

This code took a long way to have the expected result. Function references can be stored directly into the vector, making easier to call the functions, easier to understand the code and also we can get rid of 20 bytes if we also replace the n.length by three – the array won’t grow:

And the code haves too much characters on the initialization, as you can see:

First of all points, who needs the keyword var? It will be gone. The other problem, we have too many assignments, that leads to many commas… and hey. On this contest the canvas is the first element, so the code can get some advantages of the condition:

An also I took advantage of the remaining bytes to set the overflow to hidden, avoiding the scroll bars. After this bit polishing we have this code:

And If we remove all the chars that we don’t need, as spaces, 0 preceding dots and newlines we have wonderful 650 bytes instead of 818!

You may also like...