Created
December 21, 2021 14:39
-
-
Save uqmessias/3765bf29c05b347d0240a12921e92408 to your computer and use it in GitHub Desktop.
Function to transform string into base64
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
/** | |
* | |
* @param {string} str | |
*/ | |
function base64(str) { | |
const base64Characters = [ | |
"A", | |
"B", | |
"C", | |
"D", | |
"E", | |
"F", | |
"G", | |
"H", | |
"I", | |
"J", | |
"K", | |
"L", | |
"M", | |
"N", | |
"O", | |
"P", | |
"Q", | |
"R", | |
"S", | |
"T", | |
"U", | |
"V", | |
"W", | |
"X", | |
"Y", | |
"Z", | |
"a", | |
"b", | |
"c", | |
"d", | |
"e", | |
"f", | |
"g", | |
"h", | |
"i", | |
"j", | |
"k", | |
"l", | |
"m", | |
"n", | |
"o", | |
"p", | |
"q", | |
"r", | |
"s", | |
"t", | |
"u", | |
"v", | |
"w", | |
"x", | |
"y", | |
"z", | |
"0", | |
"1", | |
"2", | |
"3", | |
"4", | |
"5", | |
"6", | |
"7", | |
"8", | |
"9", | |
"+", | |
"/", | |
]; | |
const binariesGroups24bits = str.split("").reduce((groups, c) => { | |
const ascii = c.charCodeAt(0); | |
const binary = ascii.toString(2).padStart(8, "0"); | |
if (groups.length === 0 || groups[groups.length - 1].length >= 24) | |
groups.push(binary); | |
else groups[groups.length - 1] = `${groups[groups.length - 1]}${binary}`; | |
return groups; | |
}, []); | |
return binariesGroups24bits | |
.map((group) => { | |
const firstChar = group.substr(0, 6); | |
let secondChar; | |
let thirdChar; | |
let forthChar; | |
switch (group.length) { | |
case 8: | |
secondChar = group.substr(6).padEnd(6, "0"); | |
break; | |
case 16: | |
secondChar = group.substr(6, 6); | |
thirdChar = group.substr(12).padEnd(6, "0"); | |
break; | |
case 24: | |
secondChar = group.substr(6, 6); | |
thirdChar = group.substr(12, 6); | |
forthChar = group.substr(18).padEnd(6, "0"); | |
break; | |
} | |
return [firstChar, secondChar, thirdChar, forthChar] | |
.map((char) => | |
typeof char === "undefined" | |
? "=" | |
: base64Characters[parseInt(char, 2)] | |
) | |
.join(""); | |
}) | |
.join(""); | |
} | |
const input = "light work."; | |
const output = base64(input); | |
console.log( | |
`input: ${input}\n\noutput: ${output}\n\ndoes it work? `, | |
output === "bGlnaHQgd29yay4=" | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment