Skip to content

Instantly share code, notes, and snippets.

@creuserr
Last active January 22, 2024 16:14
Show Gist options
  • Save creuserr/d76b992258a7dcd77c8143d6b1f8116c to your computer and use it in GitHub Desktop.
Save creuserr/d76b992258a7dcd77c8143d6b1f8116c to your computer and use it in GitHub Desktop.
๐Ÿ—œ๏ธ Employing Cantor-Pairing for efficient compression and decompression, reducing the size of a string by half.
// Try it online:
// https://bit.ly/48ZZbOE
function compress(t) {
function pair(a, b) {
return 0.5 * (a + b) * (a + b + 1) + b;
}
return new Array(Math.ceil(t.length / 2)).fill(0).map((_, i) => String.fromCharCode(pair(t.charCodeAt(i * 2) + 1, t.charCodeAt(i * 2 + 1) + 1 || 0))).join("");
}
function decompress(t) {
function unpair(n) {
var w = Math.floor((Math.sqrt(8 * n + 1) - 1) / 2);
var t = (w ** 2 + w) / 2;
return [w - (n - t), n - t];
}
return t.split("").map(i => {
var p = unpair(i.charCodeAt(0));
return String.fromCharCode(p[0] - 1) + (p[1] == 0 ? "" : String.fromCharCode(p[1] - 1));
}).join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment