javascript lzw_encode, lzw_decode

function lzw_encode(s) {
  var d = new Date;
  var dict = {};
  var data = (s + "").split("");
  var out = [];
  var currChar;
  var phrase = data[0];
  var code = 256;
  for(var i = 1;i  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])
  }
  var retrunedresult = out.join("");
  console.log("Input: " + s.length / 1024 + "kb Output:" + retrunedresult.length / 1024 + "kb Rate: " + s.length / retrunedresult.length);
  console.log((new Date).getTime() - d.getTime() + " ms.");
  return retrunedresult
}
function lzw_decode(s) {
  var dict = {};
  var data = (s + "").split("");
  var currChar = data[0];
  var oldPhrase = currChar;
  var out = [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 = oldPhrase + currChar;
    code++;
    oldPhrase = phrase
  }
  return out.join("")
}
;
This entry was posted in Uncategorized. 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