lz-string.js
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
(function(root, factory) {
var LZW = factory();
if (typeof define !== "undefined" && define.amd) {
define(function() {
return LZW;
});
}
root.LZW = LZW;
}(window, function () {
return {
compress: function (uncompressed) {
"use strict";
// Build the dictionary.
var i,
dictionary = {},
c,
wc,
w = "",
result = [],
dictSize = Math.pow(2, 16),//Unicode字符数值最大值加一
strLength = uncompressed.length;
for (i = 0; i < strLength; i += 1) {
c = uncompressed.charAt(i);
wc = w + c;
//Do not use dictionary[wc] because javascript arrays
//will return values for array['pop'], array['push'] etc
if (dictionary.hasOwnProperty(wc)) {
w = wc;
} else {
if (w && !dictionary[w]) {
dictionary[w] = w.charCodeAt();
}
if (dictionary[w]) {
result.push(dictionary[w]);
dictionary[wc] = dictSize++;
}
// Add wc to the dictionary.
w = String(c);
}
}
// Output the code for w.
if (w !== "") {
result.push(dictionary[w] || w.charCodeAt());
}
return result.join(",");
},
decompress: function (compressed) {
"use strict";
// Build the dictionary.
var i,
dictionary = [],
w,
result,
k,
entry = "",
dictSize = Math.pow(2, 16);//Unicode字符数值最大值加一
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 {
entry = String.fromCharCode(k);
}
}
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
w = entry;
}
return result;
}
};
}));