Last active
July 26, 2019 20:52
-
-
Save karanlyons/77d3b306e1f6cbe216788edb25f99bb2 to your computer and use it in GitHub Desktop.
Char wise, byte foolish.
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
const pack = s => | |
s.match(/^[\u0000-\u00ff]*$/) | |
? s | |
.split("") | |
.map(s => s.charCodeAt()) | |
.reduce( | |
(pairs, c) => | |
( | |
!c || pairs[pairs.length - 1].length === 2 | |
? pairs.push(...(c? [[c]] : [[c], []])) | |
: pairs[pairs.length - 1].push(c) | |
) | |
&& pairs, | |
[[]] | |
) | |
.filter(pair => pair.length) | |
.map(pair => String.fromCharCode( | |
pair.length === 2? (pair[0] << 8) + pair[1] : pair[0] | |
)) | |
.join("") | |
: null; | |
const unpack = s => unescape(escape(s).replace(/u(..)/g, "$1%")); | |
const exampleStr = "This is a packed ascii string."; | |
console.log(exampleStr, exampleStr.length); // This is a packed ascii string. – 30 | |
console.log(pack(exampleStr), pack(exampleStr).length); // 周楳猠愠灡捫敤獣楩瑲楮朮 – 15 | |
console.log(exampleStr === unpack(pack(exampleStr))); // true | |
// eval('console.log("Hello!")') | |
eval(unescape(escape("捯湳潬攮汯木≈敬汯™)").replace(/u(..)/g, "$1%"))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment