class zip{
unzipStr(str) {
let Utf8ArrayToStr = function(array) { // 数据流转化为字符串, 兼容汉字
var out = "", i = 0, len = array.length, char1, char2, char3, char4;
while(i < len) {
char1 = array[i++];
// 当单个字节时, 最大值 '01111111', 最小值 '00000000' 右移四位 07, 00
// 当两个字节时, 最大值 '11011111', 最小值 '11000000' 右移四位 13, 12
// 当三个字节时, 最大值 '11101111', 最小值 '11100000' 右移四位 14, 14
if (char1 >> 4 <= 7) {
out += String.fromCharCode(char1);
} else if (char1 >> 4 == 12 || char1 >> 4 == 13) {
char2 = array[i++];
out += String.fromCharCode(((char1 & 0x1F) << 6) | (char2 & 0x3F));
} else if (char1 >> 4 == 14) {
char2 = array[i++];
char3 = array[i++];
char4 = ((char1 & 0x0F) << 12) | ((char2 & 0x3F) << 6);
out += String.fromCharCode(char4 | ((char3 & 0x3F) << 0));
}
}
return out;
};
function handleCodePoints(array) {
var CHUNK_SIZE = 0x8000; // arbitrary number here, not too small, not too big
var index = 0;
var length = array.length;
var result = '';
var slice;
var arr = [];
for(var i = 0, _i = array.length; i < _i; i++) {
arr[i] = array[i];
}
while(index < length) {
slice = arr.slice(index, Math.min(index + CHUNK_SIZE, length)); // `Math.min` is not really necessary here I think
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
return result;
}
try{
var binaryString = window.atob(str);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
var byteArray = new Uint8Array(bytes); // 切换数据编码为
byteArray = pako.ungzip(bytes); // 调用 pako 的方法解压数据
return Utf8ArrayToStr(byteArray);
}catch(e){
//TODO handle the exception
console.log(e)
return str
}
}
zipStr(str) {
var binaryString = pako.gzip(str, { to: 'string' });
return btoa(binaryString);
}
}
测试代码:
let yasuo=new zip().zipStr("我是中国人");
console.log(yasuo)
console.log(new zip().unzipStr(yasuo))
结果:
H4sIAAAAAAAAA3vWMfHZjPVPdqx9Onvvk127AGTv6cwPAAAA
mytest.html:70 我是中国人
|