public
Last active

LZW compression and decompression by @_sebastienp (not me)

  • Download Gist
annotated.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
/*
 
Copyright (c) 2011 Sebastien P.
 
http://twitter.com/_sebastienp
 
MIT licensed.
 
---
 
LZW compression/decompression attempt for 140byt.es.
 
---
 
See http://rosettacode.org/wiki/LZW_compression#JavaScript !
 
*/
 
window.LZW = {
 
// 163 bytes
compress: function (
a, // String to compress
b, // Placeholder for dictionary size
c, // Placeholder for dictionary
d, // Placeholder for iterator
e, // Placeholder for w
f, // Placeholder for result
g, // Placeholder for c
h // Placeholder for wc
) {
 
for (b = d = 256, c = {}; d--;)
 
c[String.fromCharCode(d)] = d;
 
for (f = []; g = a[++d];)
//for (e = "", f = []; g = a[++d];) // Using this one is 1 byte longer ...
 
e = c[h = e ? e + g : g] ? h : (f.push(c[e]), c[h] = b++, g);
//e = c[h = e + g] ? h : (f.push(c[e]), c[h] = b++, g); // ... but maybe faster ?
 
e && f.push(c[e]);
 
return f
 
},
 
// 158 bytes
decompress: function (
a, // Array to decompress
b, // Placeholder for dictionary size
c, // Placeholder for dictionary
d, // Placeholder for iterator
e, // Placeholder for w
f, // Placeholder for result
g, // Placeholder for entry
h // Placeholder for k
) {
 
for (b = d = 256, c = [], e = String.fromCharCode; d--;)
 
c[d] = e(d);
 
for (e = f = e(a[d = 0]); (h = a[++d]) <= b;)
 
g = c[h] || e + e[0], c[b++] = e + g[0], f += e = g;
 
return f
 
}
 
};
 
// 22 bytes --- String.fromCharCode(x)
// 28 bytes --- unescape("%"+x.toString(16))
// 29 bytes --- eval("'\\"+x.toString(8)+"'")
index.js
JavaScript
1 2 3 4
window.LZW = {
comp: function(a,b,c,d,e,f,g,h){for(b=d=256,c={};d--;)c[String.fromCharCode(d)]=d;for(f=[];g= a[++d];)e=c[h=e?e+g:g]?h:(f.push(c[e]),c[h]=b++,g);e&&f.push(c[e]);return f},
decomp: function(a,b,c,d,e,f,g,h){for(b=d=256,c=[],e=String.fromCharCode;d--;)c[d]=e(d);for(e=f=e(a[d=0]);(h=a[++d])<=b;)g=c[h]||e+e[0],c[b++]=e+g[0],f+=e=g;return f}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.