Last active
January 24, 2026 11:14
-
-
Save FND/066149fc6a9218af08c3b29ff16f540b to your computer and use it in GitHub Desktop.
text compression (JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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