Last active
June 4, 2022 05:21
unicode string encoder/decoder for ascii
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 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; | |
} |
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 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also see https://xem.github.io/codegolf/obfuscatweet.html