Created
January 24, 2015 05:23
-
-
Save anonymous/75c801c0a05e7ac3db0a to your computer and use it in GitHub Desktop.
Reasonably fast implementation of Lempel–Ziv–Welch compression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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