Skip to content

Instantly share code, notes, and snippets.

@karanlyons
Last active July 26, 2019 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karanlyons/77d3b306e1f6cbe216788edb25f99bb2 to your computer and use it in GitHub Desktop.
Save karanlyons/77d3b306e1f6cbe216788edb25f99bb2 to your computer and use it in GitHub Desktop.
Char wise, byte foolish.
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