2 years ago
#57922

hey_im_abhi
Problem with polyfill window.atob implementation inJavascript
I'm trying to write my own solution for a BFE problem https://bigfrontend.dev/problem/implement-atob
Basically, writing a polyfill for the atob function available in javascript
I tried to understand the base64 encoding/decoding process and came up with the following implementation that works fine for most inputs but some of the test cases are failing
function myAtob(encoded) {
// All base64 charset
const base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let temp = ""; // used for storing all characters to binary form
let decoded = "";
for (let i of encoded) {
// converts each encoded character to binary and pads if required
temp += base64.indexOf(i).toString(2).padStart(6, 0);
}
for (let i = 0; i < temp.length; i += 8) {
const num = temp.slice(i, i + 8); // make groups of 8 bits
const ascii = parseInt(num, 2); // convert 8 bits to number
if (ascii > 30 && ascii < 123){
// I used above 'if' for ignoring the unsupported characters
decoded += String.fromCharCode(ascii); // append string equivalent
}
}
return decoded;
}
I tried to debug and I believe it's happening because some unsupported codes or escaped characters are getting part of my output messing up the test cases.
Example when using the window.atob function,
atob("A===") throws error
atob("AA==") returns '\x00'
These are different from what my function returns. Maybe the padding character = is messing up something.
The following are test case results:
Can someone help me with fixing the logic and handling of edge cases?
javascript
base64
polyfills
0 Answers
Your Answer