AI solution for JavaScript Coding Question on BFE.dev
141. implement btoa()
One possible solution for implementing btoa()
is as follows:
function myBtoa(str) { // Define the Base64 encoding table consisting of 64 characters. const base64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Initialize the result string. let result = ''; // Convert each character of the input string to binary representation, // and group them into 3-byte chunks. for (let i = 0; i < str.length; i += 3) { let chunk = str.charCodeAt(i) << 16; // First byte of chunk. if (i + 1 < str.length) chunk |= str.charCodeAt(i + 1) << 8; // Second byte of chunk. if (i + 2 < str.length) chunk |= str.charCodeAt(i + 2); // Third byte of chunk. // Extract the 6-bit value of each Base64 digit from the chunk, // and append them to the result string. for (let j = 0; j < 4; j++) { if (i + j * 3 <= str.length) result += base64Table.charAt((chunk >> 18 - j * 6) & 0x3F); else result += '='; // Padding for incomplete final chunk. } } return result;}
Explanation:
-
The
base64Table
variable contains the 64 valid Base64 encoding characters, in the order they appear in the encoding sequence. -
The function loops over the input string, processing it in 3-byte chunks. If the string length is not a multiple of 3, padding characters ('=') are added to the last chunk so that it has exactly 3 bytes.
-
For each chunk, the function converts it to a 24-bit binary number by concatenating the 8-bit binary representation of each of its 3 bytes.
-
The function then extracts the 6-bit value of each Base64 digit from the chunk, starting from the most significant (leftmost) digit, and appends them to the result string.
-
If the input string had to be padded with one or two extra bytes to form a complete chunk, the corresponding Base64 digits of the chunk are replaced with padding characters ('='), as per the Base64 specification.
-
Finally, the function returns the completed Base64-encoded string.
Example:
myBtoa('BFE.dev') // Returns: "QkZFLmRldg=="
In this case, the input string has a length of 7 characters, which is not a multiple of 3. Therefore, two padding characters ('=') are added at the end of the encoded string to form a complete chunk of 3 bytes.