Created
April 21, 2015 17:34
-
-
Save kirilloid/e1700329f7cc971a45a8 to your computer and use it in GitHub Desktop.
lz77-alike
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
(function decompress (s) { | |
var i, c, out = "", len, offset; | |
for (i = 0; i < s.length; i++) { | |
c = s.charCodeAt(i); | |
if (c >= 256 && c <= 288) { | |
len = c - 256; | |
offset = s.charCodeAt(++i); | |
out += out.substr(-offset, len); | |
} else { | |
out += s.charAt(i); | |
} | |
} | |
return decodeURIComponent(escape(out)); | |
}(function compress (s) { | |
var i, out = [], tmp, p, b; | |
s = unescape(encodeURIComponent(s)); | |
for (i = 0; i < s.length; i++) { | |
for (b = 64; b >= 4; b--) { | |
tmp = s.substr(i, b); | |
p = s.slice(0, i).indexOf(tmp); | |
if (p > -1) { | |
out.push(256 + b, i-p); | |
i += b-1; | |
break; | |
} | |
} | |
if (b === 3) out.push(s.charCodeAt(i)); | |
} | |
return out; | |
}(str))) | |
(function huffman (s) { | |
var i, c, h = {}, a = []; | |
for (i = s.length-1; i >= 0; i--) { | |
c = s.charCodeAt(i); | |
h[c] = (h[c] || 0) + 1; | |
} | |
for (c in h) a.push([parseInt(c), h[c]]); | |
a.sort(function(a,b){ return b[1]-a[1] }); | |
var n,n1,n2; | |
while (a.length > 2) { | |
n = [[n2 = a.pop(), n1 = a.pop()], n1[1] + n2[1]] | |
for (i = a.length - 1; i >= 0 && a[i][1] < n[1]; i--); | |
a.splice(i,0,n); | |
} | |
var bits = []; | |
(function r (node, m, d) { | |
if (typeof node[0] === 'number') { | |
bits.push(1, node[0]); | |
} else { | |
bits.push(0); | |
r(node[0][0], m*2, d+1); | |
r(node[0][1], m*2+1, d+1); | |
} | |
}([a, a[0][1] + a[1][1]]), 0, 0); | |
return bits; | |
}("j'aime aller sur le bord de l'eau les jeudis ou les jours impairs")) | |
function(t){var a=[],f=0,b=0,s=function(l,n){for(f+=n<<b,b+=l;b>t;b-=t,f>>=t)a.push(f%(1<<t))}s.e=function(){return b&&a.push(f),a}return s} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment