Skip to content

Instantly share code, notes, and snippets.

@kbjr
Forked from sebastien-p/LICENSE.txt
Created June 14, 2011 09:31
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 kbjr/1024583 to your computer and use it in GitHub Desktop.
Save kbjr/1024583 to your computer and use it in GitHub Desktop.
JavaScript implementation of the Lempel–Ziv–Welch universal lossless data compression algorithm.
// Please, see http://rosettacode.org/wiki/LZW_compression#JavaScript for more infos.
// Could fail in IE because of the 'str[x]' notation, should be better to use 'str.charAt(x)'.
// Still 18 bytes to go (25 including '.charAt') !
function (
a, // String to compress
b, // Placeholder for dictionary
c, // Placeholder for dictionary size
d, // Placeholder for iterator
e, // Placeholder for w
f, // Placeholder for result
g, // Placeholder for c
h // Placeholder for wc
){
for (b = {}, c = d = 256; b[String.fromCharCode(d)] = d--;);
for (e = f = []; g = a[++d];)
e = b[h = e + g] ? h : (f.push(b[e]), b[h] = c++, g);
f.push(b[e]);
return f
}
function(a,b,c,d,e,f,g,h){for(b={},c=d=256;b[String.fromCharCode(d)]=d--;);for(e=f=[];g=a[++d];)e=b[h=e+g]?h:(f.push(b[e]),b[h]=c++,g);f.push(b[e]);return f}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Sebastien P. https://twitter.com/#!/_sebastienp
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "LZWcompress",
"description": "JavaScript implementation of the Lempel–Ziv–Welch universal lossless data compression algorithm.",
"keywords": [
"LZW",
"lossless",
"data",
"compression"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var LZWcompress = function(a,b,c,d,e,f,g,h){for(b={},c=d=256;b[String.fromCharCode(d)]=d--;);for(e=f=[];g=a[++d];)e=b[h=e+g]?h:(f.push(b[e]),b[h]=c++,g);f.push(b[e]);return f}
document.getElementById("ret").innerHTML = LZW("TOBEORNOTTOBEORTOBEORNOT")
</script>
@kbjr
Copy link
Author

kbjr commented Jun 14, 2011

I moved the

b[String.fromCharCode(d)] = d

part into the for loop allowing the removal of the second d

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