07 Apr

javascript compressor

Update: Further work has since been done on this

I was a bit bored when I got home, so decided to start on a javascript compressor. There are many of them out there already (I particularly like these two), but there is nothing quite as satisfying as your own work.

The work so far is here.

The project so far has been fascinating. I realised immediately upon starting that I couldn’t simply apply rules like “swap all multiple spaces with single spaces” and such, as that would break any strings or regular expressions in the code.

So, I’ve basically had to write a JavaScript parser – the function reads the code in, one character at a time, and decides whether to keep it or drop it.

An advantage to this is that I can segment the code into different “types” of code, allowing me to parse strings, regexps and “command”-style code differently.

I’m sure this is probably old hat to those college types who had to write compilers in class, but it’s pretty fascinating to me.

Tomorrow, I hope to detect code such as the following:

var a=function(){alert('test');}

And convert it to this:

var a=function(){alert('test')};alert(a);

In the above, note the addition of a ‘;’ after the function declaration – as far as I know, no other javascript compression code actually corrects badly written code like that. I’d like mine to be the first.

I have other plans for this, but will wait to see if I am still interested in the morning, before working on them ;-).