Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript string compression

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.

like image 743
sje397 Avatar asked Aug 15 '10 03:08

sje397


2 Answers

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).

like image 178
Alex Avatar answered Sep 29 '22 14:09

Alex


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");
like image 38
Behrang Avatar answered Sep 29 '22 14:09

Behrang