Skip to content

Instantly share code, notes, and snippets.

@Fordi
Forked from anonymous/lzw.js
Last active March 3, 2019 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fordi/bd389fde04adc6a97edf to your computer and use it in GitHub Desktop.
Save Fordi/bd389fde04adc6a97edf to your computer and use it in GitHub Desktop.
export const lzw = {
decode: 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: 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++;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
return String.fromCharCode.apply(0, out);
},
encodeObject: obj => this.encode(JSON.stringify(obj)),
decodeObject: str => JSON.parse(this.decode(str))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment