この解答例はChatGPTによって生成されています,正しいかは自己判断で。
BFE.devでのAI解答例 - JavaScript コーディング問題
141. implement btoa()
以下が自作の解答例です。
function myBtoa(str) {
const base64Chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Convert each character in the string to its ASCII code point.
const binaryStr = str
.split('')
.map(char => char.charCodeAt(0).toString(2).padStart(8, '0'))
.join('');
// Pad the binary string with zeroes to make its length a multiple of 6.
const numPaddingBytes = (6 - (binaryStr.length % 6)) % 6;
const paddedBinaryStr = binaryStr.padEnd(binaryStr.length + numPaddingBytes, '0');
// Split the binary string into chunks of 6 bits and convert each chunk to a base64 character.
const chunks = paddedBinaryStr.match(/.{6}/g);
const base64Encoded = chunks
.map(chunk => base64Chars[parseInt(chunk, 2)])
.join('');
// Add padding characters if necessary.
const numPaddingChars = numPaddingBytes / 2;
return base64Encoded.padEnd(base64Encoded.length + numPaddingChars, '=');
}
この解答では、まず各文字のASCII コードポイントを2進数文字列に変換し、それらを8桁にパディングしてバイナリ文字列に変換します。例えば、文字列 'BFE.dev' は以下のようになります。
B F E . d e v
01000010 01000110 01000101 00101110 01100100 01100101 01110110
バイナリ文字列は6ビットの塊に分割し、それぞれをBase64エンコード文字に変換します。次に、不足分がないようにパディングによってバイナリ文字列を調整し、必要に応じてBase64エンコード文字列に '=' を追加して完了します。 'BFE'と'BFE.dev'の例では、それぞれ'QkZF'と'QkZFLmRldg=='にエンコードされています。