Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit25dc6aa

Browse files
committed
LZW Encoding/Decoding
Lempel–Ziv–Welch (LZW) is a universal lossless data compressionalgorithm. It is an improved implementation of the LZ78 algorithm.
1 parent03bb9b1 commit25dc6aa

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

‎src/compression/LZW/LZW.js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/**
2+
* LZW Encoding/Decoding
3+
*
4+
* Lempel–Ziv–Welch (LZW) is a universal lossless data
5+
* compression algorithm. It is an improved implementation
6+
* of the LZ78 algorithm.
7+
*
8+
*@example
9+
* var lzwModule = require('path-to-algorithms/src/compression'+
10+
* '/LZW/LZW');
11+
* var lzw = new lzwModule.LZW();
12+
*
13+
* var compressed = lzw.compress("ABCABCABCABCABCABC");
14+
* console.log(compressed);
15+
*
16+
* var decompressed = lzw.decompress(compressed);
17+
* console.log(decompressed);
18+
*
19+
*@module compression/LZW/LZW
20+
*/
21+
(function(exports){
22+
'use strict';
23+
24+
exports.LZW=function(){
25+
this.dictionarySize=256;
26+
};
27+
28+
exports.LZW.compress=function(data){
29+
vari;
30+
vardictionary={};
31+
varcharacter;
32+
varwc;
33+
varw='';
34+
varresult=[];
35+
36+
for(i=0;i<this.dictionarySize;i=i+1){
37+
dictionary[String.fromCharCode(i)]=i;
38+
}
39+
40+
for(i=0;i<data.length;i=i+1){
41+
character=data.charAt(i);
42+
wc=w+character;
43+
if(dictionary.hasOwnProperty(wc)){
44+
w=wc;
45+
}else{
46+
result.push(dictionary[w]);
47+
dictionary[wc]=this.dictionarySize;
48+
this.dictionarySize=this.dictionarySize+1;
49+
w=String(character);
50+
}
51+
}
52+
53+
if(w!==''){
54+
result.push(dictionary[w]);
55+
}
56+
57+
returnresult;
58+
};
59+
60+
exports.LZW.decompress=function(compressedData){
61+
vari;
62+
vardictionary=[];
63+
varw;
64+
varresult;
65+
varkey;
66+
varentry='';
67+
68+
for(i=0;i<this.dictionarySize;i=i+1){
69+
dictionary[i]=String.fromCharCode(i);
70+
}
71+
72+
w=String.fromCharCode(compressedData[0]);
73+
result=w;
74+
75+
for(i=1;i<compressedData.length;i=i+1){
76+
key=compressedData[i];
77+
if(dictionary[key]){
78+
entry=dictionary[key];
79+
}else{
80+
if(key===this.dictionarySize){
81+
entry=w+w.charAt(0);
82+
}else{
83+
returnnull;
84+
}
85+
}
86+
87+
result+=entry;
88+
dictionary[this.dictionarySize]=w+entry.charAt(0);
89+
this.dictionarySize=this.dictionarySize+1;
90+
w=entry;
91+
}
92+
93+
returnresult;
94+
};
95+
})(typeofwindow==='undefined' ?module.exports :window);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp