views:

126

answers:

3

Hi All,

I'm trying to enter a javascript competition where the script has to be <= 1kb in size. Minifying and eval is allowed, so I've run it through google's closure compiler (which does slightly better than any others I've tried).

But I've found that if I convert the script to a string, and replace long words like 'function' and 'return' with single chars, I can reduce that even further. Then, by embedding the string in my script, performing the substitution to restore it, and then 'evaling' it, I can get the original behaviour.

So I was wondering if I could generalise this last method. Has anyone seen or written code to compress/decompress strings in this way? Feel like thinking about it?

EDIT To make myslelf clear, I'm asking about compressing and decompressing strings in javascript - not minifying. E.g. how to find the most common patterns in a string, and how to write a tiny decompressor in javascript for strings where these occurences have been replaced with single chars.

Thanks.

A: 

Tokenisation is the preferred method for compressing scripts as it works with the individual keywords and other names.

Delan Azabani
Most of this is done by the closure compiler - there are very few javascript keywords I'm using (function, return etc) but the closure compiler automatically makes all function names just 1 letter long, etc.
sje397
+1  A: 

Have you considered shortening your code by creating a shortcut for those JavaScript objects and methods that you use a lot in your code:

var d = document; var id = d.getElementById;

And then instead of writing

document.getElementById("foo")

You can write

id("foo");
Bytecode Ninja
Yep, done that already...but also, the closure compiler does it as part of it's optimisation as well.
sje397
+2  A: 

Do you happen to be looking for http://www.iteral.com/jscrush/ ? I found it useful for the same competition (I assume it is js1k).

Alex Nolan
Nope. That's another minifier. I'm looking to compress and decompress strings.
sje397
Apologies. That's exactly the sort of thing I was talking about.
sje397