web.btoa.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var $ = require('../internals/export');
  2. var getBuiltIn = require('../internals/get-built-in');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var fails = require('../internals/fails');
  5. var toString = require('../internals/to-string');
  6. var validateArgumentsLength = require('../internals/validate-arguments-length');
  7. var itoc = require('../internals/base64-map').itoc;
  8. var $btoa = getBuiltIn('btoa');
  9. var charAt = uncurryThis(''.charAt);
  10. var charCodeAt = uncurryThis(''.charCodeAt);
  11. var NO_ARG_RECEIVING_CHECK = !!$btoa && !fails(function () {
  12. $btoa();
  13. });
  14. var WRONG_ARG_CONVERSION = !!$btoa && fails(function () {
  15. return $btoa(null) !== 'bnVsbA==';
  16. });
  17. var WRONG_ARITY = !!$btoa && $btoa.length !== 1;
  18. // `btoa` method
  19. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  20. $({ global: true, enumerable: true, forced: NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY }, {
  21. btoa: function btoa(data) {
  22. validateArgumentsLength(arguments.length, 1);
  23. if (NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY) return $btoa(toString(data));
  24. var string = toString(data);
  25. var output = '';
  26. var position = 0;
  27. var map = itoc;
  28. var block, charCode;
  29. while (charAt(string, position) || (map = '=', position % 1)) {
  30. charCode = charCodeAt(string, position += 3 / 4);
  31. if (charCode > 0xFF) {
  32. throw new (getBuiltIn('DOMException'))('The string contains characters outside of the Latin1 range', 'InvalidCharacterError');
  33. }
  34. block = block << 8 | charCode;
  35. output += charAt(map, 63 & block >> 8 - position % 1 * 8);
  36. } return output;
  37. }
  38. });