Created
February 22, 2019 18:36
-
-
Save airarm/4547a9ca169e0046b6469fec2522583d to your computer and use it in GitHub Desktop.
Base64 javascript component
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
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; | |
export default Base64 = { | |
btoa: (input) => { | |
input = input || ''; | |
if(typeof input !== 'string'){ | |
throw new Error("Input must be string but you given "+(typeof input)); | |
} | |
let str = input; | |
let output = ''; | |
for (let block = 0, charCode, i = 0, map = chars; | |
str.charAt(i | 0) || (map = '=', i % 1); | |
output += map.charAt(63 & block >> 8 - i % 1 * 8)) { | |
charCode = str.charCodeAt(i += 3/4); | |
if (charCode > 0xFF) { | |
throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); | |
} | |
block = block << 8 | charCode; | |
} | |
return output; | |
}, | |
atob: (input) => { | |
input = input || ''; | |
if(typeof input !== 'string'){ | |
throw new Error("Input must be string but you given "+(typeof input)); | |
} | |
let str = input.replace(/=+$/, ''); | |
let output = ''; | |
if (str.length % 4 == 1) { | |
throw new Error("'atob' failed: The string to be decoded is not correctly encoded."); | |
} | |
for (let bc = 0, bs = 0, buffer, i = 0; | |
buffer = str.charAt(i++); | |
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, | |
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 | |
) { | |
buffer = chars.indexOf(buffer); | |
} | |
return output; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment