LZ77 JavaScript Implementation


LZ77 is a compression algorithm described in 1977 by Lempel and Ziv. In this page you'll find a JavaScript implementation of the LZ77 algorithm suitable for the compression and decompression of text.

You are free to use the source code in this page as you wish. There is no guarantee: use it at your own risk. A link to this page or a thank you message would be highly appreciated. Feel free to contact me for suggestions or corrections.



The first version was implemented in JavaScript. It compresses text at a speed of 200 to 1000 characters per second (depending on the compression level and the compressed text); decompression is 10 to 100 times faster than that.

There is also a more compact version of the decompress function, if you are out of space:

function dri(d,w){var v=0;for(var i=0;i<w;i++){v*=96;var c=d.charCodeAt(i);
if((c>=32)&&(c<=127)){v+=c-32;}else{throw "Invalid char code in reference int: "+c;
}}return v;}function decompress(d){var de="";var p=0;while(p<d.length){var cc=d[p];
if(cc!="`"){de+=cc;p++;}else{var nc=d.charAt[p+1];if(nc!="`"){var di=dri(d.substr(p
+1,2),2);var l=dri(d[p+3])+5;de+=de.substr(de.length-di-l,l);p+=4;}else{de+="`";p+=
2;}}}return de;}


There is also a Python version, about 10 times faster than the JavaScript one. It's useful to prepare some text to be included in a web page.

See also

Compress JavaScript source code

Compression in JavaScript

Last updated by Diogo Kollross in 2006-04-20 1