function pack16 input var result new Uint8Array input length for var i

 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
function pack16(input) {
var result = new Uint8Array(input.length * 2)
for(var i = 0; i < input.length; i++) {
result[i * 2 + 0] = (input[i] >> 8) & 0xFF
result[i * 2 + 1] = (input[i]) & 0xFF
}
return result
}
function lzw_encode(data) {
var dict = {}
for(var i = 0; i<256; ++i) {
dict[[i]] = [i];
}
var out = new Uint16Array(data.length)
var outIndex = 0
var currChar
var phrase = [ data[0] ]
var code = 256;
for (var i=1; i<data.length; i++) {
currChar = [data[i]];
if (dict.hasOwnProperty(phrase.concat(currChar))) {
phrase = phrase.concat(currChar)
} else {
var newData = phrase.length > 1 ? [dict[phrase]] : phrase
for(var index = 0; index < newData.length; ++index) {
out[outIndex] = newData[index]
outIndex += 1
}
if (code < 65535) {
var key = phrase.concat(currChar)
dict[key] = code
code = code + 1
}
phrase = currChar
}
}
var newData = phrase.length > 1 ? [dict[phrase]] : phrase
for(var index = 0; index < newData.length; ++index) {
out[outIndex] = newData[index]
outIndex += 1
}
console.log('compressed size: ', outIndex, ', dict size:', code, Object.keys(dict).length)
return out.subarray(0, outIndex )
}