index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. (function (root, factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define([], factory);
  4. } else if (typeof exports === "object") {
  5. module.exports = factory();
  6. } else {
  7. var textEncoding = factory();
  8. root.TextEncoder = textEncoding.TextEncoder;
  9. root.TextDecoder = textEncoding.TextDecoder;
  10. }
  11. }(this, function () {
  12. "use strict";
  13. // return native implementation if available
  14. var g = typeof global !== 'undefined' ? global : self;
  15. if (typeof g.TextEncoder !== 'undefined' && typeof g.TextDecoder !== 'undefined') {
  16. return {'TextEncoder': g.TextEncoder, 'TextDecoder': g.TextDecoder};
  17. }
  18. // allowed encoding strings for utf-8
  19. var utf8Encodings = [
  20. 'utf8',
  21. 'utf-8',
  22. 'unicode-1-1-utf-8'
  23. ];
  24. var TextEncoder = function(encoding) {
  25. if (utf8Encodings.indexOf(encoding) < 0 && typeof encoding !== 'undefined' && encoding !== null) {
  26. throw new RangeError('Invalid encoding type. Only utf-8 is supported');
  27. } else {
  28. this.encoding = 'utf-8';
  29. this.encode = function(str) {
  30. if (typeof str !== 'string') {
  31. throw new TypeError('passed argument must be of type string');
  32. }
  33. var binstr = unescape(encodeURIComponent(str)),
  34. arr = new Uint8Array(binstr.length);
  35. binstr.split('').forEach(function(char, i) {
  36. arr[i] = char.charCodeAt(0);
  37. });
  38. return arr;
  39. };
  40. }
  41. };
  42. var TextDecoder = function(encoding, options) {
  43. if (utf8Encodings.indexOf(encoding) < 0 && typeof encoding !== 'undefined' && encoding !== null) {
  44. throw new RangeError('Invalid encoding type. Only utf-8 is supported');
  45. }
  46. this.encoding = 'utf-8';
  47. this.ignoreBOM = false;
  48. this.fatal = (typeof options !== 'undefined' && 'fatal' in options) ? options.fatal : false;
  49. if (typeof this.fatal !== 'boolean') {
  50. throw new TypeError('fatal flag must be boolean');
  51. }
  52. this.decode = function (view, options) {
  53. if (typeof view === 'undefined') {
  54. return '';
  55. }
  56. var stream = (typeof options !== 'undefined' && 'stream' in options) ? options.stream : false;
  57. if (typeof stream !== 'boolean') {
  58. throw new TypeError('stream option must be boolean');
  59. }
  60. if (!ArrayBuffer.isView(view)) {
  61. throw new TypeError('passed argument must be an array buffer view');
  62. } else {
  63. var arr = new Uint8Array(view.buffer, view.byteOffset, view.byteLength),
  64. charArr = new Array(arr.length);
  65. arr.forEach(function(charcode, i) {
  66. charArr[i] = String.fromCharCode(charcode);
  67. });
  68. return decodeURIComponent(escape(charArr.join('')));
  69. }
  70. };
  71. };
  72. return {'TextEncoder': TextEncoder, 'TextDecoder': TextDecoder};
  73. }));