JavaScript implementation of Gzip

 JavaScript implementation of Gzip

jsolait library

// LZW-compress a string
function lzw_encode(s){
    var dict ={};
    var data =(s +"").split("");
    varout=[];
    var currChar;
    var phrase = data[0];
    var code =256;
    for(var i=1; i<data.length; i++){
        currChar=data[i];
        if(dict[phrase + currChar]!=null){
            phrase += currChar;
        }
        else{
            out.push(phrase.length >1? dict[phrase]: phrase.charCodeAt(0));
            dict[phrase + currChar]= code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length >1? dict[phrase]: phrase.charCodeAt(0));
    for(var i=0; i<out.length; i++){
        out[i]=String.fromCharCode(out[i]);
    }
    returnout.join("");
}

// Decompress an LZW-encoded string
function lzw_decode(s){
    var dict ={};
    var data =(s +"").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    varout=[currChar];
    var code =256;
    var phrase;
    for(var i=1; i<data.length; i++){
        var currCode = data[i].charCodeAt(0);
        if(currCode <256){
            phrase = data[i];
        }
        else{
           phrase = dict[currCode]? dict[currCode]:(oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code]= oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    returnout.join("");
}
This entry was posted in Code Snippets. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s