0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript: なまくらLZW

Last updated at Posted at 2024-12-29

LZW

かつて一世を風靡した情報圧縮法。これ無しでは世界は回らなかった程で、圧縮界の頂点に君臨し続けた訳が無い。

実装編

LZWの超単純で制約もりもりの実装。してその制約とは…

  • Unicode番号0-255に対応した文字列のみ処理可能。当然surrogate pairなどというものには未対応
  • 辞書番号の最大値は65535
  • 出力文はUTF8形式文字列
  • 圧縮率がごみ
function LZWe(c){
	for(var d=[],e={__proto__:null},f=c.split(""),a=f[0],b=0,g=256,l=f.length,h=0,S=String.fromCharCode;++b<l;e[a+c]?a+=c:(d[h++]=1<a.length?S(e[a]):a,e[a+c]=g++,a=c))c=f[b];
	d[h]=1<a.length?S(e[a]):a;
	return d.join("")
}
function LZWd(b){
	for(var a,e={__proto__:null},d=b.split(""),c=d[0],f=c,g=[c],h=256,o=h,l=d.length,i=b=0;++b<l;f=a)a=d[b].charCodeAt(),g[++i]=a=h>a?d[b]:e[a]||f+c,c=a.charAt(),e[o++]=f+c;
	return g.join("")
}
利用例
var c="HTMLAnchorElement HTMLAreaElement HTMLAudioElement",
	e=LZWe(c),
	d=LZWd(e);
console.log(d.length,"->",new TextEncoder().ecode(e).length,c==d)

執行

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?