Skip to content

Instantly share code, notes, and snippets.

@jamesbjackson
Forked from sebastien-p/LICENSE.txt
Created December 2, 2011 00:43
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 jamesbjackson/1421033 to your computer and use it in GitHub Desktop.
Save jamesbjackson/1421033 to your computer and use it in GitHub Desktop.
LZW compression
// Please, see http://rosettacode.org/wiki/LZW_compression#JavaScript
// and http://en.wikipedia.org/wiki/Lempel–Ziv–Welch for more infos.
function (
a // String to compress and placeholder for 'wc'.
){
for (
var b = a + "Ā", // Append first "illegal" character (charCode === 256).
c = [], // dictionary
d = 0, // dictionary size
e = d, // iterator
f = c, // w
g = c, // result
h; // c
h = b.charAt(e++);
)
c[h] = h.charCodeAt(), // Fill in the dictionary ...
f = 1 + c[a = f + h] ? a : (g[d++] = c[f], c[a] = d + 255, h); // ... and use it to compress data.
return g // Array of compressed data.
}
function(a){for(var b=a+"Ā",c=[],d=0,e=d,f=c,g=c,h;h=b.charAt(e++);)c[h]=h.charCodeAt(),f=1+c[a=f+h]?a:(g[d++]=c[f],c[a]=d+255,h);return g}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Sebastien P. https://twitter.com/#!/_sebastienp
Special thanks to @subzey (you rock) and @kbjr !
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){for(var b=a+"Ā",c=[],d=0,e=d,f=c,g=c,h;h=b.charAt(e++);)c[h]=h.charCodeAt(),f=1+c[a=f+h]?a:(g[d++]=c[f],c[a]=d+255,h);return g}
document.getElementById("ret").innerHTML = LZWcompress("TOBEORNOTTOBEORTOBEORNOT")
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment