Last active
April 22, 2022 12:40
-
-
Save mizchi/721d781d02ed821ad6dd7283b512b0b8 to your computer and use it in GitHub Desktop.
This file contains 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
declare const DecompressionStream: any; | |
declare const CompressionStream: any; | |
const encoder = new TextEncoder(); | |
const decoder = new TextDecoder(); | |
async function compress(str: string): Promise<ArrayBuffer> { | |
const cs = new CompressionStream("gzip"); | |
const buf = encoder.encode(str); | |
const stream = new Response(buf).body!.pipeThrough(cs); | |
return new Response(stream as any).arrayBuffer(); | |
} | |
async function decompress(buffer: ArrayBuffer): Promise<string> { | |
const ds = new DecompressionStream("gzip"); | |
const decompressedStream = new Blob([buffer]).stream().pipeThrough(ds); | |
const buf = await new Response(decompressedStream as any).arrayBuffer(); | |
return decoder.decode(buf); | |
} | |
async function main() { | |
const json = { a: 1 }; | |
const str = JSON.stringify(json); | |
const compressed = await compress(str); | |
const restored = await decompress(compressed); | |
console.assert(str === restored); | |
} | |
main(); |
Author
mizchi
commented
Apr 22, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment