Skip to content

Instantly share code, notes, and snippets.

@tabrindle
Created September 12, 2013 13:44
Show Gist options
  • Save tabrindle/6537604 to your computer and use it in GitHub Desktop.
Save tabrindle/6537604 to your computer and use it in GitHub Desktop.
two functions for lzw encoding and decoding.
lzw_encode: function(s) {
var dict = {};
var data = (s + '').split('');
var out = [];
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]);
}
return out.join('');
},
lzw_decode: function(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[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join('');
}
@JavaScript-Packer
Copy link

function lzw_encode(r) {
  var n, h, a = {}, e = (r + "").split(""), v = [], t = e[0], o = 256;
  for (h = 1; h < e.length; h++) {
    n = e[h], null != a[t + n] ? t += n : (v.push(t.length > 1 ? a[t] : t.charCodeAt(0)), 
    a[t + n] = o, o++, t = n);
  }
  for (v.push(t.length > 1 ? a[t] : t.charCodeAt(0)), h = 0; h < v.length; h++) {
    v[h] = String.fromCharCode(v[h]);
  }
  return v.join("");
}

function lzw_decode(r) {
  var h, l, i, a = {}, e = (r + "").split(""), v = e[0], n = v, t = [ v ], o = 256;
  for (l = 1; l < e.length; l++) {
    i = e[l].charCodeAt(0), h = 256 > i ? e[l] : a[i] ? a[i] : n + v, t.push(h), v = h.charAt(0), 
    a[o] = n + v, o++, n = h;
  }
  return t.join("");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment