Skip to content

Instantly share code, notes, and snippets.

@shakahl
Forked from Explosion-Scratch/Compress string.js
Created January 17, 2024 07:22
Show Gist options
  • Save shakahl/5d0e9fb561c117237100bd27dd30c9ad to your computer and use it in GitHub Desktop.
Save shakahl/5d0e9fb561c117237100bd27dd30c9ad to your computer and use it in GitHub Desktop.
Compress string using gzip and native browser APIs
function compress(string, encoding) {
const byteArray = new TextEncoder().encode(string);
const cs = new CompressionStream(encoding);
const writer = cs.writable.getWriter();
writer.write(byteArray);
writer.close();
return new Response(cs.readable).arrayBuffer();
}
function decompress(byteArray, encoding) {
const cs = new DecompressionStream(encoding);
const writer = cs.writable.getWriter();
writer.write(byteArray);
writer.close();
return new Response(cs.readable).arrayBuffer().then(function (arrayBuffer) {
return new TextDecoder().decode(arrayBuffer);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment