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 )
}