@base-web-kits/base-tools-ts 0.9.5 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base-tools-ts.umd.global.js +2 -1
- package/dist/base-tools-ts.umd.global.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -0
- package/package.json +9 -17
- package/src/ts/array/index.ts +13 -0
- package/src/ts/async/index.ts +20 -0
- package/src/ts/bean/EventBus.ts +61 -0
- package/src/ts/bean/index.ts +1 -0
- package/src/ts/day/index.ts +184 -0
- package/src/ts/index.ts +14 -0
- package/src/ts/lodash/index.ts +7 -0
- package/src/ts/number/big.ts +192 -0
- package/src/ts/number/format.ts +253 -0
- package/src/ts/number/index.ts +3 -0
- package/src/ts/number/random.ts +65 -0
- package/src/ts/object/index.ts +12 -0
- package/src/ts/string/format.ts +52 -0
- package/src/ts/string/index.ts +3 -0
- package/src/ts/string/other.ts +33 -0
- package/src/ts/string/random.ts +42 -0
- package/src/ts/typing/index.ts +161 -0
- package/src/ts/url/file/index.ts +57 -0
- package/src/ts/url/index.ts +4 -0
- package/src/ts/url/oss/index.d.ts +120 -0
- package/src/ts/url/oss/index.ts +168 -0
- package/src/ts/url/param/index.ts +119 -0
- package/src/ts/url/qn/index.d.ts +103 -0
- package/src/ts/url/qn/index.ts +237 -0
- package/src/ts/validator/index.ts +601 -0
- package/base-tools-ts.umd.global.js +0 -10619
- package/index.cjs +0 -2
- package/index.d.ts +0 -1
- package/index.js +0 -1
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { BigNumber } from './big';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 开头补零
|
|
5
|
+
* @param n 数字
|
|
6
|
+
* @param len 总长度,默认 2
|
|
7
|
+
* @returns 零填充后的字符串
|
|
8
|
+
* @example
|
|
9
|
+
* zeroPad(1) // '01'
|
|
10
|
+
* zeroPad(12) // '12'
|
|
11
|
+
* zeroPad(12, 4) // '0012'
|
|
12
|
+
*/
|
|
13
|
+
export function zeroPad(n: number | string, len = 2) {
|
|
14
|
+
return String(n).padStart(len, '0');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 给数字添加指定单位 (支持数字字符串,其他非法字符返回原值)
|
|
19
|
+
* @param unit 单位
|
|
20
|
+
* @param num 数字
|
|
21
|
+
* @example
|
|
22
|
+
* withUnit(0, 'px') // "0px"
|
|
23
|
+
* withUnit(1, 'px') // "1px"
|
|
24
|
+
* withUnit('1', 'rpx') // "1rpx"
|
|
25
|
+
* withUnit('1', '%') // "1%"
|
|
26
|
+
* withUnit('auto', 'px') // "auto"
|
|
27
|
+
* withUnit(null | undefined | '') // ""
|
|
28
|
+
*/
|
|
29
|
+
export function withUnit(num?: number | string, unit = '') {
|
|
30
|
+
if (num === null || num === undefined || num === '') return ''; // 注意不能排除0
|
|
31
|
+
|
|
32
|
+
if (typeof num === 'number') return `${num}${unit}`;
|
|
33
|
+
|
|
34
|
+
const str = String(num).trim();
|
|
35
|
+
|
|
36
|
+
if (str === '') return '';
|
|
37
|
+
|
|
38
|
+
return isNaN(+str) ? str : `${str}${unit}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 给数字添加px单位 (支持数字字符串,其他非法字符返回原值)
|
|
43
|
+
* @example
|
|
44
|
+
* withUnitPx(10) // "10px"
|
|
45
|
+
* withUnitPx('10') // "10px"
|
|
46
|
+
* withUnitPx('10px') // "10px"
|
|
47
|
+
* withUnitPx("auto") // "auto"
|
|
48
|
+
* withUnitPx("30%") // "30%"
|
|
49
|
+
* withUnitPx(null | undefined | '') // ""
|
|
50
|
+
* withUnitPx(0) // "0px"
|
|
51
|
+
*/
|
|
52
|
+
export function withUnitPx(num?: string | number) {
|
|
53
|
+
return withUnit(num, 'px');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 给数字添加距离单位:当数值大于等于 1000m 时转换为 km,否则显示 m(最多两位小数、无无意义补零)
|
|
58
|
+
* @example
|
|
59
|
+
* withDistance(5); // => '5m'
|
|
60
|
+
* withDistance(999.456); // => '999.46m'
|
|
61
|
+
* withDistance(1000); // => '1km'
|
|
62
|
+
* withDistance('1500'); // => '1.5km'
|
|
63
|
+
* withDistance('1728'); // => '1.73km'
|
|
64
|
+
*/
|
|
65
|
+
export function withDistance(m: number | string): string {
|
|
66
|
+
const n = Number(m ?? 0);
|
|
67
|
+
if (!Number.isFinite(n)) return '0m';
|
|
68
|
+
return n >= 1000 ? `${+(n / 1000).toFixed(2)}km` : `${+n.toFixed(2)}m`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 数字转千分位字符串(保留小数与符号)。
|
|
73
|
+
* @example
|
|
74
|
+
* toThousandth(1234567); // => '1,234,567'
|
|
75
|
+
* toThousandth('1234567.89'); // => '1,234,567.89'
|
|
76
|
+
* toThousandth('-987654'); // => '-987,654'
|
|
77
|
+
*/
|
|
78
|
+
export function toThousandth(str: number | string): string {
|
|
79
|
+
const v = String(str ?? '').trim();
|
|
80
|
+
if (v === '') return '';
|
|
81
|
+
|
|
82
|
+
// 处理符号
|
|
83
|
+
let sign = '';
|
|
84
|
+
let num = v;
|
|
85
|
+
if (num[0] === '-' || num[0] === '+') {
|
|
86
|
+
sign = num[0];
|
|
87
|
+
num = num.slice(1);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 拆分整数与小数部分
|
|
91
|
+
const [intPart, decPart] = num.split('.');
|
|
92
|
+
|
|
93
|
+
// 仅对整数部分进行千分位分组
|
|
94
|
+
const groupedInt = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
95
|
+
|
|
96
|
+
return decPart !== undefined && decPart !== ''
|
|
97
|
+
? `${sign}${groupedInt}.${decPart}`
|
|
98
|
+
: `${sign}${groupedInt}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 阿拉伯数字转中文整数(忽略小数;支持负数)。
|
|
103
|
+
* @param num 输入的数字或数字字符串(小数部分将被丢弃)
|
|
104
|
+
* @returns 中文数字字符串;非法输入返回空字符串
|
|
105
|
+
* @example
|
|
106
|
+
* toChineseNum(123456); // "十二万三千四百五十六"
|
|
107
|
+
* toChineseNum(-10008); // "负一万零八"
|
|
108
|
+
* `第${toChineseNum(123)}条` // "第一百二十三条"
|
|
109
|
+
*/
|
|
110
|
+
export function toChineseNum(num: number | string) {
|
|
111
|
+
const numInt = Math.trunc(+num);
|
|
112
|
+
if (numInt === 0) return '零';
|
|
113
|
+
|
|
114
|
+
const digit = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
|
|
115
|
+
const unit = ['', '十', '百', '千'];
|
|
116
|
+
const bigUnit = ['', '万', '亿', '兆'];
|
|
117
|
+
|
|
118
|
+
const section4 = (n: number) => {
|
|
119
|
+
let str = '',
|
|
120
|
+
zeroFlag = false;
|
|
121
|
+
for (let i = 0; i < 4; i++) {
|
|
122
|
+
const d = n % 10;
|
|
123
|
+
n = Math.floor(n / 10);
|
|
124
|
+
if (d === 0) {
|
|
125
|
+
zeroFlag = true;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (zeroFlag) str = digit[0] + str;
|
|
129
|
+
str = digit[d] + unit[i] + str;
|
|
130
|
+
zeroFlag = false;
|
|
131
|
+
}
|
|
132
|
+
return str;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
let res = '';
|
|
136
|
+
let sectionIndex = 0;
|
|
137
|
+
let n = Math.abs(numInt);
|
|
138
|
+
|
|
139
|
+
while (n > 0) {
|
|
140
|
+
const seg = n % 10000;
|
|
141
|
+
n = Math.floor(n / 10000);
|
|
142
|
+
if (seg) {
|
|
143
|
+
const segStr = section4(seg);
|
|
144
|
+
res = segStr + (sectionIndex ? bigUnit[sectionIndex] : '') + res;
|
|
145
|
+
} else if (res && !res.startsWith('零')) {
|
|
146
|
+
res = `零${res}`;
|
|
147
|
+
}
|
|
148
|
+
sectionIndex++;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
res = res.replace(/^一十/, '十');
|
|
152
|
+
|
|
153
|
+
return numInt < 0 ? `负${res}` : res;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 金额转中文大写(支持角/分/厘,精度控制)。
|
|
158
|
+
* @param amount 金额(支持 number | string),非法或非有限数返回空串
|
|
159
|
+
* @param opts 配置项
|
|
160
|
+
* @param opts.precision 保留小数位(0~3),对应:0无小数、1角、2角分、3角分厘;默认 2
|
|
161
|
+
* @param opts.rm 舍入模式,默认 `BigNumber.ROUND_HALF_UP`(四舍五入)
|
|
162
|
+
* @param opts.yuanChar 元单位字符(`'元' | '圆'`),默认 `'元'`
|
|
163
|
+
* @returns 中文大写金额字符串;示例:`壹佰贰拾叁元肆角伍分`
|
|
164
|
+
* @example
|
|
165
|
+
* toChineseCurrency(0) // '零元整'
|
|
166
|
+
* toChineseCurrency(10) // '拾元整'
|
|
167
|
+
* toChineseCurrency(101) // '壹佰零壹元整'
|
|
168
|
+
* toChineseCurrency(1001000) // '壹佰万零壹仟元整'
|
|
169
|
+
* toChineseCurrency(1001.01) // '壹仟零壹元壹分'
|
|
170
|
+
* toChineseCurrency('1234.5679', { precision: 3 }) // '壹仟贰佰叁拾肆元伍角陆分捌厘'
|
|
171
|
+
* toChineseCurrency(-1.2) // '负壹元贰角'
|
|
172
|
+
*/
|
|
173
|
+
export function toChineseCurrency(
|
|
174
|
+
amount: number | string,
|
|
175
|
+
opts: {
|
|
176
|
+
precision?: 0 | 1 | 2 | 3;
|
|
177
|
+
rm?: BigNumber.RoundingMode;
|
|
178
|
+
yuanChar?: '元' | '圆';
|
|
179
|
+
} = {},
|
|
180
|
+
): string {
|
|
181
|
+
const dp = opts.precision ?? 2;
|
|
182
|
+
const rm = opts.rm ?? BigNumber.ROUND_HALF_UP;
|
|
183
|
+
const yuan = opts.yuanChar ?? '元';
|
|
184
|
+
|
|
185
|
+
// 1. 非法输入直接返回空串
|
|
186
|
+
if (amount === null || amount === undefined) return '';
|
|
187
|
+
const bn = new BigNumber(amount);
|
|
188
|
+
if (!bn.isFinite()) return '';
|
|
189
|
+
|
|
190
|
+
// 2. 转字符串并拆分整数/小数
|
|
191
|
+
const s = bn.toFixed(dp, rm);
|
|
192
|
+
const sign = s.startsWith('-') ? '负' : '';
|
|
193
|
+
const [intStr, decStr = ''] = s.replace(/^-/, '').split('.');
|
|
194
|
+
|
|
195
|
+
// 3. 数字与大写映射
|
|
196
|
+
const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
|
|
197
|
+
const unit = ['', '拾', '佰', '仟'];
|
|
198
|
+
const bigUnit = ['', '万', '亿', '兆'];
|
|
199
|
+
const smallUnit = ['角', '分', '厘'];
|
|
200
|
+
|
|
201
|
+
// 4. 四位一段转换整数
|
|
202
|
+
const section4 = (n: BigNumber): string => {
|
|
203
|
+
let str = '';
|
|
204
|
+
let zeroFlag = false;
|
|
205
|
+
for (let i = 0; i < 4; i++) {
|
|
206
|
+
const d = n.mod(10).toNumber();
|
|
207
|
+
n = n.idiv(10);
|
|
208
|
+
if (d === 0) {
|
|
209
|
+
zeroFlag = true;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (zeroFlag) str = digit[0] + str;
|
|
213
|
+
str = digit[d] + unit[i] + str;
|
|
214
|
+
zeroFlag = false;
|
|
215
|
+
}
|
|
216
|
+
return str.replace(/零+$/g, '');
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const intNum = new BigNumber(intStr);
|
|
220
|
+
let res = '';
|
|
221
|
+
if (intNum.isZero()) {
|
|
222
|
+
res = digit[0];
|
|
223
|
+
} else {
|
|
224
|
+
let n = intNum.abs();
|
|
225
|
+
let sectionIndex = 0;
|
|
226
|
+
while (n.gt(0)) {
|
|
227
|
+
const seg = n.mod(10000);
|
|
228
|
+
n = n.idiv(10000);
|
|
229
|
+
if (seg.gt(0)) {
|
|
230
|
+
const segStr = section4(seg);
|
|
231
|
+
const needZero =
|
|
232
|
+
res && !res.startsWith(digit[0]) && (seg.lt(1000) || seg.mod(1000).isZero());
|
|
233
|
+
const bu = sectionIndex ? bigUnit[sectionIndex] : '';
|
|
234
|
+
res = segStr + bu + (needZero ? digit[0] : '') + res;
|
|
235
|
+
} else if (res && !res.startsWith(digit[0])) {
|
|
236
|
+
res = digit[0] + res;
|
|
237
|
+
}
|
|
238
|
+
sectionIndex++;
|
|
239
|
+
}
|
|
240
|
+
res = res.replace(/^壹拾/, '拾');
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// 5. 小数部分(角分厘)
|
|
244
|
+
let frac = '';
|
|
245
|
+
for (let i = 0; i < Math.min(3, dp); i++) {
|
|
246
|
+
const ch = decStr[i] || '0';
|
|
247
|
+
const d = ch.charCodeAt(0) - 48;
|
|
248
|
+
if (d > 0) frac += digit[d] + smallUnit[i];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 6. 拼接
|
|
252
|
+
return frac ? `${sign}${res}${yuan}${frac}` : `${sign}${res}${yuan}整`;
|
|
253
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 随机生成 `a` 到 `b` 的整数(闭区间,包含两端)。
|
|
3
|
+
* - 自动交换边界,按从小到大处理。
|
|
4
|
+
* - 下界向上取整、上界向下取整后再取值。
|
|
5
|
+
* @param a 边界值。
|
|
6
|
+
* @param b 边界值。
|
|
7
|
+
* @returns 闭区间内的随机整数。
|
|
8
|
+
* @example
|
|
9
|
+
* randomInt(0, 10); // => 0..10 之间的随机整数(含 0 与 10)
|
|
10
|
+
* randomInt(10, 0); // => 0..10 之间的随机整数(含 0 与 10)
|
|
11
|
+
* randomInt(5.2, 10.8); // => 6..10 之间取整随机数(含 6 与 10)
|
|
12
|
+
*/
|
|
13
|
+
export function randomInt(a: number, b: number): number {
|
|
14
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) {
|
|
15
|
+
throw new TypeError('min 和 max 必须是有限数值');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const low = Math.min(a, b);
|
|
19
|
+
const high = Math.max(a, b);
|
|
20
|
+
|
|
21
|
+
const minInt = Math.ceil(low);
|
|
22
|
+
const maxInt = Math.floor(high);
|
|
23
|
+
|
|
24
|
+
if (maxInt < minInt) {
|
|
25
|
+
throw new RangeError('取整后区间为空');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (maxInt === minInt) return minInt;
|
|
29
|
+
|
|
30
|
+
return Math.floor(Math.random() * (maxInt - minInt + 1)) + minInt;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 随机生成 `a` 到 `b` 的浮点数(半开区间,包含下界不包含上界)。
|
|
35
|
+
* - 自动交换边界,按从小到大处理。
|
|
36
|
+
* @param a 边界值。
|
|
37
|
+
* @param b 边界值。
|
|
38
|
+
* @returns 半开区间内的随机浮点数。
|
|
39
|
+
* @example
|
|
40
|
+
* randomFloat(0, 10); // => [0, 10) 内的随机浮点数
|
|
41
|
+
* randomFloat(10, 0); // => [0, 10) 内的随机浮点数
|
|
42
|
+
* randomFloat(5.2, 10.8); // => [5.2, 10.8) 内的随机浮点数
|
|
43
|
+
*/
|
|
44
|
+
export function randomFloat(a: number, b: number): number {
|
|
45
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) {
|
|
46
|
+
throw new TypeError('min 和 max 必须是有限数值');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const low = Math.min(a, b);
|
|
50
|
+
const high = Math.max(a, b);
|
|
51
|
+
|
|
52
|
+
if (high === low) return low;
|
|
53
|
+
|
|
54
|
+
return Math.random() * (high - low) + low;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 随机生成一个布尔值。
|
|
59
|
+
* @returns 随机布尔值。
|
|
60
|
+
* @example
|
|
61
|
+
* randomBoolean(); // => 随机返回 true 或 false
|
|
62
|
+
*/
|
|
63
|
+
export function randomBoolean(): boolean {
|
|
64
|
+
return Math.random() < 0.5;
|
|
65
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 获取对象键名数组(类型安全)。
|
|
3
|
+
* 注:内置 `Object.keys` 与 `lodash-es` 的 `keys` 在 TS 中通常返回 `string[]`,无法精确到 `keyof T`。
|
|
4
|
+
* @param obj 目标对象
|
|
5
|
+
* @returns 类型精确的 `Array<keyof T>`
|
|
6
|
+
* @example
|
|
7
|
+
* const o = { a: 1, b: 'x' };
|
|
8
|
+
* const keys = getObjectKeys(o); // type: ('a' | 'b')[], value: ['a','b']
|
|
9
|
+
*/
|
|
10
|
+
export function getObjectKeys<T extends object>(obj: T): Array<keyof T> {
|
|
11
|
+
return Object.keys(obj) as (keyof T)[];
|
|
12
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文本脱敏
|
|
3
|
+
* @param s 原始文本
|
|
4
|
+
* @param keepLeft 保留左侧字符数(默认 1)
|
|
5
|
+
* @param keepRight 保留右侧字符数(默认 0)
|
|
6
|
+
* @param maskChar 脱敏字符(默认 `*`)
|
|
7
|
+
* @returns 脱敏文本
|
|
8
|
+
* @example
|
|
9
|
+
* toMaskText('王小明', 1, 0) // => '王*'
|
|
10
|
+
* toMaskText('王小明', 1, 1) // => '王*明'
|
|
11
|
+
* toMaskText('13800138000', 3, 4) // => '138****8000'
|
|
12
|
+
*/
|
|
13
|
+
export function toMaskText(s: string, keepLeft = 1, keepRight = 0, maskChar = '*') {
|
|
14
|
+
if (!s) return '';
|
|
15
|
+
const v = String(s);
|
|
16
|
+
const l = Math.max(0, keepLeft);
|
|
17
|
+
const r = Math.max(0, keepRight);
|
|
18
|
+
const len = v.length;
|
|
19
|
+
const left = Math.min(l, len);
|
|
20
|
+
const right = Math.min(r, len - left);
|
|
21
|
+
const mid = len - left - right;
|
|
22
|
+
if (mid <= 0) return v;
|
|
23
|
+
const m = maskChar && maskChar.length > 0 ? maskChar : '*';
|
|
24
|
+
return v.slice(0, left) + m.repeat(mid) + v.slice(len - right);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 手机号中间打星:保留前三位与后四位,中间打 `*`。
|
|
29
|
+
* @param phone 手机号字符串
|
|
30
|
+
* @returns 遮蔽后的手机号
|
|
31
|
+
* @example
|
|
32
|
+
* toMaskPhone('13800138000') // => '138****8000'
|
|
33
|
+
*/
|
|
34
|
+
export function toMaskPhone(phone: string) {
|
|
35
|
+
return toMaskText(phone, 3, 4);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 姓名打星:
|
|
40
|
+
* - 长度 ≤ 2:保留首字,其余打 `*`
|
|
41
|
+
* - 长度 ≥ 3:保留首尾,各打星中间
|
|
42
|
+
* @param name 姓名字符串
|
|
43
|
+
* @returns 遮蔽后的姓名
|
|
44
|
+
* @example
|
|
45
|
+
* toMaskName('张三') // => '张*'
|
|
46
|
+
* toMaskName('王小明') // => '王*明'
|
|
47
|
+
*/
|
|
48
|
+
export function toMaskName(name: string) {
|
|
49
|
+
if (!name) return '';
|
|
50
|
+
const v = String(name);
|
|
51
|
+
return v.length <= 2 ? toMaskText(v, 1, 0) : toMaskText(v, 1, 1);
|
|
52
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 计算字符串在 UTF-8 编码下的字节长度。
|
|
3
|
+
* 使用场景:
|
|
4
|
+
* 1) 按字节限制表单输入(避免超过后端/数据库字段上限)
|
|
5
|
+
* 2) 评估网络传输、缓存(Redis/消息队列)开销
|
|
6
|
+
* 3) 根据字节数截断或提示用户(而非按字符数)
|
|
7
|
+
* @param str 输入的字符串
|
|
8
|
+
* @returns 字符串的字节长度
|
|
9
|
+
* @example
|
|
10
|
+
* getStringByteLength('abc') // 3
|
|
11
|
+
* getStringByteLength('中文') // 6
|
|
12
|
+
* getStringByteLength('😊') // 4
|
|
13
|
+
*/
|
|
14
|
+
export function getStringByteLength(str: string): number {
|
|
15
|
+
let byteLen = 0;
|
|
16
|
+
|
|
17
|
+
for (let i = 0; i < str.length; i++) {
|
|
18
|
+
const code = str.charCodeAt(i);
|
|
19
|
+
|
|
20
|
+
if (code <= 0x7f) {
|
|
21
|
+
byteLen += 1; // (ASCII 基本拉丁)→ 包含数字 0-9、英文字母 A-Z/a-z、常见符号
|
|
22
|
+
} else if (code <= 0x7ff) {
|
|
23
|
+
byteLen += 2; // (拉丁扩展)→ 包含拉丁字母(含变音符)、希腊文、俄文/西里尔文、希伯来文、阿拉伯文等
|
|
24
|
+
} else if (code >= 0xd800 && code <= 0xdbff) {
|
|
25
|
+
byteLen += 4; // (UTF-16 代理项)→ 包含 emoji、稀有汉字(扩展区)、音乐符号等
|
|
26
|
+
i++;
|
|
27
|
+
} else {
|
|
28
|
+
byteLen += 3; // (BMP 绝大部分)→ 包含中文/日文/韩文的大多数字符(CJK 统一汉字)、以及大量其它脚本
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return byteLen;
|
|
33
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 生成UUID
|
|
3
|
+
* @returns UUID字符串
|
|
4
|
+
* @example
|
|
5
|
+
* const uuid = createUUID() // '7982fcfe-5721-4632-bede-6000885be57d'
|
|
6
|
+
*/
|
|
7
|
+
export function createUUID() {
|
|
8
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
|
9
|
+
const r = (Math.random() * 16) | 0,
|
|
10
|
+
v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
11
|
+
return v.toString(16);
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 生成随机字符串id
|
|
17
|
+
* - 常用于生成元素标签的id (默认加上'id_'前缀, 避免小程序中数字开头的id导致查询节点信息失败)
|
|
18
|
+
* @param prefix 前缀, 默认 'id_'
|
|
19
|
+
* @returns 随机字符串
|
|
20
|
+
* @example
|
|
21
|
+
* const id = createRandId(); // 'id_0rjuuuqv60xi'
|
|
22
|
+
* const id = createRandId('canvas_'); // 'canvas_v82a7ctm09q'
|
|
23
|
+
*/
|
|
24
|
+
export function createRandId(prefix = 'id_') {
|
|
25
|
+
return `${prefix}${Math.random().toString(36).substring(2, 16)}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 时间+固定位数的随机数字字符串
|
|
30
|
+
* @param digits 随机部分的位数,默认 6
|
|
31
|
+
* @returns 时间+随机数字字符串
|
|
32
|
+
* @example
|
|
33
|
+
* const traceId = createTimeRandId(); // '1763002648039123456'
|
|
34
|
+
* const traceId = createTimeRandId(8); // '176300264803912345678'
|
|
35
|
+
*/
|
|
36
|
+
export function createTimeRandId(digits: number = 6) {
|
|
37
|
+
const base = 10 ** (digits - 1);
|
|
38
|
+
const range = 9 * base;
|
|
39
|
+
const randomInt = Math.floor(Math.random() * range) + base;
|
|
40
|
+
|
|
41
|
+
return `${Date.now()}${randomInt}`;
|
|
42
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 将指定属性设为必填(不改变其他属性)。
|
|
3
|
+
* - 所有属性必填请使用内置的Required<T>
|
|
4
|
+
* @example
|
|
5
|
+
* type User = { id?: number; name?: string; age?: number };
|
|
6
|
+
* type U1 = SetRequired<User, 'id' | 'name'>; // { id: number; name: string; age?: number }
|
|
7
|
+
*/
|
|
8
|
+
export type SetRequired<T, K extends keyof T> = {
|
|
9
|
+
[P in K]-?: T[P];
|
|
10
|
+
} & Omit<T, K>;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 将指定属性设为可选(不改变其他属性)。
|
|
14
|
+
* - 所有属性可选请使用内置的Partial<T>
|
|
15
|
+
* @example
|
|
16
|
+
* type User = { id: number; name: string; age: number };
|
|
17
|
+
* type U2 = SetOptional<User, 'age'>; // { id: number; name: string; age?: number }
|
|
18
|
+
*/
|
|
19
|
+
export type SetOptional<T, K extends keyof T> = {
|
|
20
|
+
[P in K]+?: T[P];
|
|
21
|
+
} & Omit<T, K>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 深度可选(递归将所有属性设为可选)。
|
|
25
|
+
* @example
|
|
26
|
+
* type T = { a: { b: number }; list: Array<{ id: string }> };
|
|
27
|
+
* type R = DeepPartial<T>;
|
|
28
|
+
*/
|
|
29
|
+
export type DeepPartial<T> = T extends (infer U)[]
|
|
30
|
+
? DeepPartial<U>[]
|
|
31
|
+
: T extends (...args: unknown[]) => unknown
|
|
32
|
+
? T
|
|
33
|
+
: T extends object
|
|
34
|
+
? { [K in keyof T]?: DeepPartial<T[K]> }
|
|
35
|
+
: T;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 深度必填(递归移除所有可选标记)。
|
|
39
|
+
* @example
|
|
40
|
+
* type T = { a?: { b?: number } };
|
|
41
|
+
* type R = DeepRequired<T>; // { a: { b: number } }
|
|
42
|
+
*/
|
|
43
|
+
export type DeepRequired<T> = T extends (infer U)[]
|
|
44
|
+
? DeepRequired<U>[]
|
|
45
|
+
: T extends (...args: unknown[]) => unknown
|
|
46
|
+
? T
|
|
47
|
+
: T extends object
|
|
48
|
+
? { [K in keyof T]-?: DeepRequired<T[K]> }
|
|
49
|
+
: T;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 取消只读(顶层移除 `readonly`)。
|
|
53
|
+
* @example
|
|
54
|
+
* type R = Mutable<Readonly<{ a: number }>>; // { a: number }
|
|
55
|
+
*/
|
|
56
|
+
export type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 深度只读(递归添加 `readonly`)。
|
|
60
|
+
* @example
|
|
61
|
+
* type R = ReadonlyDeep<{ a: { b: number }; list: { id: string }[] }>;
|
|
62
|
+
*/
|
|
63
|
+
export type ReadonlyDeep<T> = T extends (infer U)[]
|
|
64
|
+
? ReadonlyArray<ReadonlyDeep<U>>
|
|
65
|
+
: T extends (...args: unknown[]) => unknown
|
|
66
|
+
? T
|
|
67
|
+
: T extends object
|
|
68
|
+
? { readonly [K in keyof T]: ReadonlyDeep<T[K]> }
|
|
69
|
+
: T;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 对象值联合类型。
|
|
73
|
+
* @example
|
|
74
|
+
* type V = ValueOf<{ a: 1; b: 'x' }>; // 1 | 'x'
|
|
75
|
+
*/
|
|
76
|
+
export type ValueOf<T> = T[keyof T];
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 根据值类型获取键名联合。
|
|
80
|
+
* @example
|
|
81
|
+
* type Keys = KeysOfType<{ a: string; b: number; c: string }, string>; // 'a' | 'c'
|
|
82
|
+
*/
|
|
83
|
+
export type KeysOfType<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 按值类型挑选属性。
|
|
87
|
+
* @example
|
|
88
|
+
* type R = PickByType<{ a: string; b: number; c: string }, string>; // { a: string; c: string }
|
|
89
|
+
*/
|
|
90
|
+
export type PickByType<T, V> = Pick<T, KeysOfType<T, V>>;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 可选键名联合。
|
|
94
|
+
* @example
|
|
95
|
+
* type K = OptionalKeys<{ a?: number; b: string }>; // 'a'
|
|
96
|
+
*/
|
|
97
|
+
export type OptionalKeys<T> = {
|
|
98
|
+
[K in keyof T]-?: Pick<T, K> extends Required<Pick<T, K>> ? never : K;
|
|
99
|
+
}[keyof T];
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 必填键名联合。
|
|
103
|
+
* @example
|
|
104
|
+
* type K = RequiredKeys<{ a?: number; b: string }>; // 'b'
|
|
105
|
+
*/
|
|
106
|
+
export type RequiredKeys<T> = {
|
|
107
|
+
[K in keyof T]-?: Pick<T, K> extends Required<Pick<T, K>> ? K : never;
|
|
108
|
+
}[keyof T];
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 联合类型转交叉类型。
|
|
112
|
+
* @example
|
|
113
|
+
* type I = UnionToIntersection<{ a: 1 } | { b: 2 }>; // { a: 1 } & { b: 2 }
|
|
114
|
+
*/
|
|
115
|
+
export type UnionToIntersection<U> = (U extends unknown ? (x: U) => unknown : never) extends (
|
|
116
|
+
x: infer I,
|
|
117
|
+
) => unknown
|
|
118
|
+
? I
|
|
119
|
+
: never;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 合并属性(以 `U` 覆盖 `T` 的同名属性)。
|
|
123
|
+
* @example
|
|
124
|
+
* type R = Merge<{ a: 1; b: 2 }, { b: 3; c: 4 }>; // { a: 1; b: 3; c: 4 }
|
|
125
|
+
*/
|
|
126
|
+
export type Merge<T, U> = Omit<T, keyof U> & U;
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 名义类型(品牌化)。
|
|
130
|
+
* @example
|
|
131
|
+
* type UserId = Brand<number, 'UserId'>;
|
|
132
|
+
*/
|
|
133
|
+
export type Brand<T, B extends string> = T & { readonly __brand: B };
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 可空(包含 `null | undefined`)。
|
|
137
|
+
* @example
|
|
138
|
+
* type R = Nullable<string>; // string | null | undefined
|
|
139
|
+
*/
|
|
140
|
+
export type Nullable<T> = T | null | undefined;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 可序列化为 JSON 的值类型。
|
|
144
|
+
*/
|
|
145
|
+
export type JsonPrimitive = string | number | boolean | null;
|
|
146
|
+
export type JsonObject = { [k: string]: JsonValue };
|
|
147
|
+
export type JsonArray = Array<JsonValue>;
|
|
148
|
+
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 精确匹配形状(不允许多余属性)。
|
|
152
|
+
* @example
|
|
153
|
+
* type Shape = { a: number };
|
|
154
|
+
* type OK = Exact<{ a: number }, Shape>; // { a: number }
|
|
155
|
+
* type NG = Exact<{ a: number; b: 1 }, Shape>; // never
|
|
156
|
+
*/
|
|
157
|
+
export type Exact<T, Shape> = T extends Shape
|
|
158
|
+
? Exclude<keyof T, keyof Shape> extends never
|
|
159
|
+
? T
|
|
160
|
+
: never
|
|
161
|
+
: never;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { getObjectKeys } from '../../object';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 跨端 100% 原生可解码文件后缀表
|
|
5
|
+
* 覆盖:iOS 14+ / Android 5+ WebView、Chrome/Edge/Safari/Firefox
|
|
6
|
+
* 剔除:所有需要 polyfill 或转码的容器/编码
|
|
7
|
+
*/
|
|
8
|
+
const FILE_TYPE = {
|
|
9
|
+
img: ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'],
|
|
10
|
+
video: ['mp4', 'mov', 'm4v'],
|
|
11
|
+
voice: ['mp3', 'wav', 'm4a'],
|
|
12
|
+
excel: ['csv', 'xls', 'xlsx', 'xlsm', 'ods'],
|
|
13
|
+
word: ['txt', 'doc', 'docx', 'pdf', 'md', 'wps'],
|
|
14
|
+
zip: ['zip', 'gz', 'tar', 'rar', '7z'],
|
|
15
|
+
ppt: ['ppt', 'pptx', 'odp'],
|
|
16
|
+
app: ['apk', 'ipa'],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 获取文件后缀(不含点,返回小写)。
|
|
21
|
+
* 当文件名不包含点('.')时,返回空字符串。
|
|
22
|
+
* @param fileName 文件名,例如 `avatar.PNG`
|
|
23
|
+
* @returns 后缀字符串,例如 `png`
|
|
24
|
+
* @example getFileSuffix('avatar.PNG') // 'png'
|
|
25
|
+
* @example getFileSuffix('a.tar.gz') // 'gz'
|
|
26
|
+
* @example getFileSuffix('.ignore') // ''
|
|
27
|
+
* @example getFileSuffix('abc') // ''
|
|
28
|
+
*/
|
|
29
|
+
export function getFileSuffix(fileName: string) {
|
|
30
|
+
if (fileName.startsWith('.')) return ''; // 隐藏文件,返回空串
|
|
31
|
+
|
|
32
|
+
const idx = fileName.lastIndexOf('.');
|
|
33
|
+
return idx > 0 ? fileName.slice(idx + 1).toLowerCase() : '';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 根据文件后缀判断文件类型。
|
|
38
|
+
* 会将后缀转换为小写后与 `FILE_TYPE` 映射匹配;若未匹配到则返回 `'unknown'`。
|
|
39
|
+
* @param fileName 文件名
|
|
40
|
+
* @returns 文件类型字符串(如 'img' | 'video' | 'voice' | 'excel' | 'word' | 'zip' | 'ppt' | 'app' | 'unknown')
|
|
41
|
+
* @example getFileType('avatar.PNG') // 'img'
|
|
42
|
+
* @example getFileType('archive.tar') // 'zip'
|
|
43
|
+
* @example getFileType('abc') // 'unknown'
|
|
44
|
+
*/
|
|
45
|
+
export function getFileType(fileName: string) {
|
|
46
|
+
const suffix = getFileSuffix(fileName);
|
|
47
|
+
if (!suffix) return 'unknown';
|
|
48
|
+
|
|
49
|
+
const keys = getObjectKeys(FILE_TYPE);
|
|
50
|
+
for (const key of keys) {
|
|
51
|
+
if (FILE_TYPE[key].includes(suffix)) {
|
|
52
|
+
return key;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return 'unknown';
|
|
57
|
+
}
|