btoa.js 928 B

123456789101112131415161718192021222324
  1. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  2. module.exports = function(string) {
  3. string = String(string);
  4. var bitmap, a, b, c,
  5. result = "",
  6. i = 0,
  7. rest = string.length % 3; // To determine the final padding
  8. for (; i < string.length;) {
  9. if ((a = string.charCodeAt(i++)) > 255 ||
  10. (b = string.charCodeAt(i++)) > 255 ||
  11. (c = string.charCodeAt(i++)) > 255)
  12. throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");
  13. bitmap = (a << 16) | (b << 8) | c;
  14. result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) +
  15. b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
  16. }
  17. // If there's need of padding, replace the last 'A's with equal signs
  18. return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
  19. };