Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created May 29, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/2d1b4d26fc0d816c16e1671e19cb0a49 to your computer and use it in GitHub Desktop.
Save mizchi/2d1b4d26fc0d816c16e1671e19cb0a49 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.11/pako.js"></script>
<script type="module">
async function compressToUint8Array(input) {
const cs = new CompressionStream("deflate");
const writer = cs.writable.getWriter();
writer.write(input);
writer.close();
const output = [];
const reader = cs.readable.getReader();
let totalSize = 0;
while (true) {
const { value, done } = await reader.read();
if (done) break;
output.push(value);
totalSize += value.byteLength;
}
const concatenated = new Uint8Array(totalSize);
let offset = 0;
for (const array of output) {
concatenated.set(array, offset);
offset += array.byteLength;
}
return concatenated;
}
function decompressToUint8Array(uint8Array) {
const inflator = new pako.Inflate();
inflator.push(uint8Array, false);
const output = inflator.result;
return output;
}
function stringToUint8Array(src) {
return new Uint8Array([].map.call(src, (c) => c.charCodeAt(0))).buffer;
}
function uint8ArrayToString(uint8Array) {
return String.fromCharCode.apply(null, uint8Array);
}
(async () => {
// compress
const input = "hello, hello, hello, xxx";
const buf = stringToUint8Array(input);
const compressed = await compressToUint8Array(buf);
// decompress
const restored = decompressToUint8Array(compressed);
console.log(uint8ArrayToString(restored));
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment