Skip to content

Instantly share code, notes, and snippets.

Created January 24, 2015 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/75c801c0a05e7ac3db0a to your computer and use it in GitHub Desktop.
Save anonymous/75c801c0a05e7ac3db0a to your computer and use it in GitHub Desktop.
Reasonably fast implementation of Lempel–Ziv–Welch compression
lzw = {
decode: function (str) {
var i, code, phrase,
dict = {},
chr = str[0],
last = chr,
out = [chr],
next = 256;
for (i = 1; i < str.length; i++) {
code = str[i].charCodeAt(0);
phrase = code < 256 ? str[i] : (dict[code] ? dict[code] : (last + chr));
out.push(phrase);
dict[next++] = last + (chr = phrase[0]);
last = phrase;
}
return out.join('');
},
encode: function (str) {
var chr, i,
dict = {},
out = [],
phrase = str[0],
code = 256;
for (i = 1; i < str.length; i++) {
chr = str[i];
if (dict[phrase + chr] != null) {
phrase += chr;
} else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + (phrase = chr)] = code++;
phrase = chr;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
return String.fromCharCode.apply(0, out);
},
encodeObject: function (obj) {
return this.encode(JSON.stringify(obj));
},
decodeObject: function (str) {
return JSON.parse(this.decode(str));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment