Skip to content

Instantly share code, notes, and snippets.

@jczimm
Last active June 4, 2022 05:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jczimm/1d25621243e02cf0373061d38e68d6d5 to your computer and use it in GitHub Desktop.
Save jczimm/1d25621243e02cf0373061d38e68d6d5 to your computer and use it in GitHub Desktop.
unicode string encoder/decoder for ascii
const toHexCharCode = char => char.charCodeAt(0).toString(16).padStart(2, '0');
function encodeGolf(plain) {
return unescape( // enter unicode escape codes land
plain.match(/[\s\S]{1,2}/g) // split string into pairs of letters
.map(([a, b]) => b ? '%uD8' + toHexCharCode(a) + '%uDC' + toHexCharCode(b) : a) // encode each pair as a high surrogate and low surrogate in unicode (where an odd character, just include it unencoded to preserve odd length)
.join('') // concatenate the escape codes as a string
); // exit escape codes land; return actual unicode characters
}
// 5 bytes fewer than decode
function decodeGolf(encoded) {
return unescape( // enter unicode escape codes land
escape(encoded) // convert the input into escape codes
.replace(/u../g, '') // strip the first two code digits (marker for high/low surrogate) to encode the implanted ascii character
); // exit escape codes land; return the plaintext
}
// minified
const decodeGolf_minifiedSource = encodedSource => `unescape(escape\`${encodedSource}\`.replace(/u../g,''))`;
function golfSource(source) {
const encodedSource = encodeGolf(source);
const autoRunningEncodedSource = `eval(${decodeGolf_minifiedSource(encodedSource)})`;
return autoRunningEncodedSource;
}
const toHexCharCode = char => char.charCodeAt(0).toString(16).padStart(2, '0');
function encode(plain) {
return unescape( // enter unicode escape codes land
plain.match(/[\s\S]{1,2}/g) // split string into pairs of letters
.map(([a, b]) => b ? '%u' + toHexCharCode(a) + toHexCharCode(b) : a) // encode each pair as a unicode escape code (where an odd character, just include it unencoded to preserve odd length)
.join('') // concatenate the escape codes as a string
); // exit escape codes land; return actual unicode characters
}
function decode(encoded) {
return unescape( // enter unicode escape codes land
escape(encoded) // convert the input into escape codes
.replace(/u(..)/g, '$1%') // map each first two code digits to a separate code to encode an ascii character
); // exit escape codes land; return the plaintext
}
@jczimm
Copy link
Author

jczimm commented Jun 4, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment