import pako from "pako";
const zip = (data) => {
if (!data) return data;
const dataJson =
typeof data !== "string" && typeof data !== "number"
? JSON.stringify(data)
: data;
const str = encodeURIComponent(dataJson);
const binaryString = pako.gzip(str);
const arr = Array.from(binaryString);
let s = "";
arr.forEach((item) => {
s += String.fromCharCode(item);
});
return btoa(s);
};
const chunk = 8 * 1024;
const unzip = (compressedData) => {
const strData = atob(compressedData);
const charData = strData.split("").map(function (x) {
return x.charCodeAt(0);
});
const binData = new Uint8Array(charData);
const data = pako.ungzip(binData);
let str = "";
let i;
for (i = 0; i < data.length / chunk; i++) {
str += String.fromCharCode(...data.slice(i * chunk, (i + 1) * chunk));
}
str += String.fromCharCode(...data.slice(i * chunk));
const unzipStr = decodeURIComponent(str);
let result = "";
try {
result = JSON.parse(unzipStr);
} catch (_) {
result = unzipStr;
}
return result;
};
export { zip, unzip };