Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 94a316a

Browse files
committed
Merge pull request mgechev#55 from FilipeFalcaoBatista/lzw-compression
LZW Encoding/Decoding
2 parents 9a437b1 + 25dc6aa commit 94a316a

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+
var i;
30+
var dictionary = {};
31+
var character;
32+
var wc;
33+
var w = '';
34+
var result = [];
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+
return result;
58+
};
59+
60+
exports.LZW.decompress = function (compressedData) {
61+
var i;
62+
var dictionary = [];
63+
var w;
64+
var result;
65+
var key;
66+
var entry = '';
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+
return null;
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+
return result;
94+
};
95+
})(typeof window === 'undefined' ? module.exports : window);

0 commit comments

Comments
 (0)