How might window.btoa() be implemented in JS?
Updated
•1 min read/**
* @param {string} b
* @returns {string}
*/
const btoa = (b) => {
let s = '';
const bytes = new Uint8Array(b.split('').map(x => x.charCodeAt(0)));
const ALPHABET_TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
for (let i = 0; i < bytes.length; i += 3) {
const group = new Uint8Array(
[
bytes.at(i) ?? 0x00,
bytes.at(i+1) ?? 0x00,
bytes.at(i+2) ?? 0x00,
],
);
const egroup = new Uint8Array(4);
egroup[0] = (group[0] >> 2) & 0x3f;
egroup[1] = (((group[0] << 6) | (group[1] >> 2)) >> 2) & 0x3f;
egroup[2] = (((group[1] << 4) | (group[2] >> 4)) >> 2) & 0x3f;
egroup[3] = group[2] & 0x3f;
if (bytes.at(i+2) == undefined) egroup[3] = 64;
if (bytes.at(i+1) == undefined) egroup[2] = egroup[3] = 64;
s += ALPHABET_TABLE[egroup[0]];
s += ALPHABET_TABLE[egroup[1]];
s += ALPHABET_TABLE[egroup[2]];
s += ALPHABET_TABLE[egroup[3]];
}
return s;
};
console.log(
btoa('The quick brown fox jumps over the brown dog'),
);
https://gist.github.com/fuadop/63a7fc0e032176103e70e45c21b79375
