Last active
October 2, 2020 15:52
-
-
Save nullableVoidPtr/c6d49e01b499c5d8756860f4df0e05c4 to your computer and use it in GitHub Desktop.
'functional' {a,b}to{b,a} implementation with no named functions or loops
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 btoa = input => | |
(output => | |
(length => | |
length % 3 ? | |
output.slice(0, (length % 3) - 3) + "=".repeat(3 - (length % 3)) : | |
output | |
)(input.length) | |
)(input.replace(/.{1,3}/g, chunk => | |
(f => | |
(x => | |
f((v, w) => | |
x(x)(v, w) | |
) | |
)(x => | |
f((v, w) => | |
x(x)(v, w) | |
) | |
) | |
)(encodeFunc => | |
(byteTriple, index) => | |
index < 4 ? | |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[(byteTriple >> ((3 - index) * 6)) & 63] + encodeFunc(byteTriple, index + 1) : | |
"" | |
)(chunk.split("").reduce((bitstring, byte, index) => | |
bitstring | byte.charCodeAt(0) << ((2 - index) * 8), 0 | |
), 0) | |
)); | |
const atob = encoded => | |
(encoded => { | |
if (/^([a-zA-Z0-9+/]+=*)?$/.test(encoded = encoded.replace(/[\t\n\f\r ]+/g, "")) && | |
(encoded = encoded.replace(/=*$/, "")).length !== 1) | |
return encoded.replace(/.{1,4}/g, chunk => | |
(output => | |
(length => | |
(length % 4) > 1 ? | |
output.slice(0, -[2, 1][(length % 4) - 2]) : | |
output | |
)(chunk.length) | |
)((f => | |
(x => | |
f((v, w) => | |
x(x)(v, w) | |
) | |
)(x => | |
f((v, w) => | |
x(x)(v, w) | |
) | |
) | |
)(decodeFunc => | |
(byteTriple, index) => | |
index < 3 ? | |
String.fromCharCode(byteTriple >> ((2 - index) * 8) & 0xFF) + decodeFunc(byteTriple, index + 1) : | |
"" | |
)(chunk.split("").map(c => | |
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.indexOf(c) | |
).reduce((bitstring, sextet, index) => | |
bitstring | sextet << ((3 - index) * 6), 0 | |
), 0) | |
)) | |
else | |
throw 'Incorrect encoded string'; | |
})(encoded); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why