polyfill.js
2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* @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
}
}