Skip to content

Instantly share code, notes, and snippets.

@nthung2112
Created November 14, 2025 06:43
Show Gist options
  • Select an option

  • Save nthung2112/2fb594f31e7bd4d90a7a6b786c009ea7 to your computer and use it in GitHub Desktop.

Select an option

Save nthung2112/2fb594f31e7bd4d90a7a6b786c009ea7 to your computer and use it in GitHub Desktop.
Serialize and Deserialize text
import { deflate, inflate } from "pako";
// import { fromUint8Array, toUint8Array } from 'js-base64';
interface Serde {
serialize: (state: string) => string;
deserialize: (state: string) => string;
}
const fromUint8Array = (u8a: Uint8Array) => {
const maxargs = 0x10_00;
const strs: string[] = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
strs.push(String.fromCharCode(...u8a.subarray(i, i + maxargs)));
}
return btoa(strs.join(""));
};
const tidyB64 = (s: string) => s.replace(/[^A-Za-z0-9\+\/]/g, "");
const unURI = (a: string) => tidyB64(a.replace(/[-_]/g, (m0) => (m0 == "-" ? "+" : "/")));
const mkUriSafe = (src: string) =>
src.replace(/=/g, "").replace(/[+\/]/g, (m0) => (m0 == "+" ? "-" : "_"));
const toUint8Array = (a: string) =>
Uint8Array.from(
atob(a)
.split("")
.map((c) => c.charCodeAt(0))
);
export const pakoSerde: Serde = {
serialize: (state: string): string => {
const data = new TextEncoder().encode(state);
const compressed = deflate(data, { level: 9 });
const str = fromUint8Array(compressed);
return mkUriSafe(str);
},
deserialize: (state: string): string => {
const data = toUint8Array(unURI(state));
return inflate(data, { to: "string" });
},
};
function main() {
const original = `
{
"name": "serde",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"js-base64": "^3.7.8",
"pako": "^2.1.0"
},
"devDependencies": {
"@types/pako": "^2.0.4"
}
}
`;
const compressed = pakoSerde.serialize(original);
console.log("Compressed:", compressed);
console.log("Length:", compressed.length);
const decompressed = pakoSerde.deserialize(compressed);
// console.log("Decompressed:", decompressed);
console.log("Original Length", decompressed.length);
console.log("Compression percentage:", (1 - compressed.length / original.length) * 100);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment