polyfill.js 2.75 KB
/*
 * @Date: 2026-01-07 21:19:46
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2026-01-24 12:44:01
 * @FilePath: /xyxBooking-weapp/src/utils/polyfill.js
 * @Description: 文件描述
 */

/**
 * @description 小程序环境 Polyfill:TextEncoder/TextDecoder
 * - 部分运行时(尤其是低版本基础库)可能缺少 TextEncoder/TextDecoder
 * - NFC/二维码等场景会用到 TextDecoder/TextEncoder(例如解析 NDEF)
 */

if (typeof TextEncoder === 'undefined') {
  class TextEncoder {
    /**
     * @description 将字符串编码为 UTF-8 字节数组
     * @param {string} str 待编码字符串
     * @returns {Uint8Array} UTF-8 字节数组
     */
    encode(str) {
      const len = str.length;
      const res = [];
      for (let i = 0; i < len; i++) {
        let point = str.charCodeAt(i);
        if (point <= 0x007f) {
          res.push(point);
        } else if (point <= 0x07ff) {
          res.push(0xc0 | (point >>> 6));
          res.push(0x80 | (0x3f & point));
        } else if (point <= 0xffff) {
          res.push(0xe0 | (point >>> 12));
          res.push(0x80 | (0x3f & (point >>> 6)));
          res.push(0x80 | (0x3f & point));
        } else {
          point = 0x10000 + ((point - 0xd800) << 10) + (str.charCodeAt(++i) - 0xdc00);
          res.push(0xf0 | (point >>> 18));
          res.push(0x80 | (0x3f & (point >>> 12)));
          res.push(0x80 | (0x3f & (point >>> 6)));
          res.push(0x80 | (0x3f & point));
        }
      }
      return new Uint8Array(res);
    }
  }

  if (typeof globalThis !== 'undefined') {
    globalThis.TextEncoder = TextEncoder;
  }
  if (typeof global !== 'undefined') {
    global.TextEncoder = TextEncoder;
  }
  if (typeof window !== 'undefined') {
    window.TextEncoder = TextEncoder;
  }
}

if (typeof TextDecoder === 'undefined') {
  class TextDecoder {
    /**
     * @description 将字节数据解码为字符串(简化 UTF-8 解码)
     * @param {ArrayBuffer|Uint8Array} view 字节数据
     * @param {Object} options 预留参数(与标准接口对齐)
     * @returns {string} 解码后的字符串
     */
    decode(view, options) {
      void options;
      if (!view) {
        return '';
      }
      let string = '';
      const arr = new Uint8Array(view);
      for (let i = 0; i < arr.length; i++) {
        string += String.fromCharCode(arr[i]);
      }
      try {
          // 简单的 UTF-8 解码尝试
          return decodeURIComponent(escape(string));
      } catch (e) {
          return string;
      }
    }
  }
  if (typeof globalThis !== 'undefined') {
    globalThis.TextDecoder = TextDecoder;
  }
  if (typeof global !== 'undefined') {
    global.TextDecoder = TextDecoder;
  }
  if (typeof window !== 'undefined') {
    window.TextDecoder = TextDecoder;
  }
}