Skip to content

Instantly share code, notes, and snippets.

@nullableVoidPtr
Last active October 2, 2020 15:52
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 nullableVoidPtr/c6d49e01b499c5d8756860f4df0e05c4 to your computer and use it in GitHub Desktop.
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
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);
@pl4nty
Copy link

pl4nty commented Jul 5, 2020

why

@nullableVoidPtr
Copy link
Author

why not

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