If you are looking for a JavaScript code for compressing/decompressing algorithms, you have come to the right place. In this post, I will explain the following points:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Get JSON Data From Controller</title>
</head>
<body>
<div>
<input type="button" id="compresss" value="compresss" onclick="GetcompressData();" />
<input type="button" id="uncompress" value="uncompress" onclick="Getuncompressed();" />
</div>
</body>
</html>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
var LZW = {
compress: function (uncompressed) {
"use strict";
var i,
dictionary = {},
c,
wc,
w = "",
result = [],
dictSize = 256;
for (i = 0; i < 256; i += 1) {
dictionary[String.fromCharCode(i)] = i;
}
for (i = 0; i < uncompressed.length; i += 1) {
c = uncompressed.charAt(i);
wc = w + c;
if (dictionary.hasOwnProperty(wc)) {
w = wc;
} else {
result.push(dictionary[w]);
dictionary[wc] = dictSize++;
w = String(c);
}
}
if (w !== "") {
result.push(dictionary[w]);
}
return result;
},
decompress: function (compressed) {
"use strict";
var i,
dictionary = [],
w,
result,
k,
entry = "",
dictSize = 256;
for (i = 0; i < 256; i += 1) {
dictionary[i] = String.fromCharCode(i);
}
w = String.fromCharCode(compressed[0]);
result = w;
for (i = 1; i < compressed.length; i += 1) {
k = compressed[i];
if (dictionary[k]) {
entry = dictionary[k];
} else {
if (k === dictSize) {
entry = w + w.charAt(0);
} else {
return null;
}
}
result += entry;
dictionary[dictSize++] = w + entry.charAt(0);
w = entry;
}
return result;
}
}
var employees = [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
];
function Getuncompressed() {
var str = JSON.stringify(employees)
var compressdata = LZW.compress(str)
var uncompressdata = LZW.decompress(compressdata)
alert(uncompressdata)
}
function GetcompressData() {
var str = JSON.stringify(employees)
var compressdata = LZW.compress(str)
alert(compressdata)
}
</script>
Compressed Data:
Uncompressed Data:
This JavaScript code defines an implementation of the LZW compression algorithm and provides two functions to demonstrate compression and decompression of JSON data.
LZW Compression and Decompression Functions:
Data Preparation and Compression Demo:
The GetcompressData function:
Decompression Demo: