btoa.js 986 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. // btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
  3. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  4. function E() {
  5. this.message = 'String contains an invalid character';
  6. }
  7. E.prototype = new Error;
  8. E.prototype.code = 5;
  9. E.prototype.name = 'InvalidCharacterError';
  10. function btoa(input) {
  11. var str = String(input);
  12. var output = '';
  13. for (
  14. // initialize result and counter
  15. var block, charCode, idx = 0, map = chars;
  16. // if the next str index does not exist:
  17. // change the mapping table to "="
  18. // check if d has no fractional digits
  19. str.charAt(idx | 0) || (map = '=', idx % 1);
  20. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  21. output += map.charAt(63 & block >> 8 - idx % 1 * 8)
  22. ) {
  23. charCode = str.charCodeAt(idx += 3 / 4);
  24. if (charCode > 0xFF) {
  25. throw new E();
  26. }
  27. block = block << 8 | charCode;
  28. }
  29. return output;
  30. }
  31. module.exports = btoa;