Skip to content

Instantly share code, notes, and snippets.

@FND
Last active January 24, 2026 11:14
Show Gist options
  • Select an option

  • Save FND/066149fc6a9218af08c3b29ff16f540b to your computer and use it in GitHub Desktop.

Select an option

Save FND/066149fc6a9218af08c3b29ff16f540b to your computer and use it in GitHub Desktop.
text compression (JavaScript)
let txt = crypto.randomUUID().repeat(10);
console.log(txt.length, "characters (uncompressed)");
let data = await compress(txt);
console.log(data.byteLength, "bytes (compressed)");
console.log(data.toBase64().length, "characters (compressed, Base64)");
/**
* @param {string} txt
* @returns {Promise<Uint8Array>}
*/
async function compress(txt) {
let stream = txt2stream(txt)
.pipeThrough(new TextEncoderStream())
.pipeThrough(new CompressionStream("gzip"));
let blob = await new Response(stream).blob();
return blob.bytes();
}
/** @param {string} txt */
// XXX: this becomes obsolete once `ReadableStream.from` is widely available
function txt2stream(txt) {
return new ReadableStream({
start(controller) {
controller.enqueue(txt);
controller.close();
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment