| 17 | // ==================== LZW压缩算法 ==================== |
| 18 | |
| 19 | function lzwCompress(data, bits, charFunc) { |
| 20 | if (data == null) return ''; |
| 21 | |
| 22 | let dict = {}; |
| 23 | let dictToCreate = {}; |
| 24 | let c; |
| 25 | let wc; |
| 26 | let w = ''; |
| 27 | let enlargeIn = 2; |
| 28 | let dictSize = 3; |
| 29 | let numBits = 2; |
| 30 | let result = []; |
| 31 | let value = 0; |
| 32 | let position = 0; |
| 33 | |
| 34 | for (let i = 0; i < data.length; i++) { |
| 35 | c = data.charAt(i); |
| 36 | |
| 37 | if (!Object.prototype.hasOwnProperty.call(dict, c)) { |
| 38 | dict[c] = dictSize++; |
| 39 | dictToCreate[c] = true; |
| 40 | } |
| 41 | |
| 42 | wc = w + c; |
| 43 | |
| 44 | if (Object.prototype.hasOwnProperty.call(dict, wc)) { |
| 45 | w = wc; |
| 46 | } else { |
| 47 | if (Object.prototype.hasOwnProperty.call(dictToCreate, w)) { |
| 48 | if (w.charCodeAt(0) < 256) { |
| 49 | for (let j = 0; j < numBits; j++) { |
| 50 | value = (value << 1); |
| 51 | if (position === bits - 1) { |
| 52 | position = 0; |
| 53 | result.push(charFunc(value)); |
| 54 | value = 0; |
| 55 | } else { |
| 56 | position++; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | let charCode = w.charCodeAt(0); |
| 61 | for (let j = 0; j < 8; j++) { |
| 62 | value = (value << 1) | (charCode & 1); |
| 63 | if (position === bits - 1) { |
| 64 | position = 0; |
| 65 | result.push(charFunc(value)); |
| 66 | value = 0; |
| 67 | } else { |
| 68 | position++; |
| 69 | } |
| 70 | charCode >>= 1; |
| 71 | } |
| 72 | } else { |
| 73 | let charCode = 1; |
| 74 | for (let j = 0; j < numBits; j++) { |
| 75 | value = (value << 1) | charCode; |
| 76 | if (position === bits - 1) { |