a-js-tools 1.0.13-beta.0 → 1.0.13-beta.1

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/index.cjs.js CHANGED
@@ -1,37 +1,867 @@
1
1
  'use strict';
2
2
 
3
- var createConstructor = require('./src/object/createConstructor.cjs.js');
4
- var getRandomNumber = require('./src/getRandomNumber.cjs.js');
5
- var className = require('./src/className.cjs.js');
6
- var getRandomString = require('./src/getRandomString.cjs.js');
7
- var performance = require('./src/performance.cjs.js');
8
- var escapeRegExp = require('./src/regexp/escapeRegExp.cjs.js');
9
- var autoEscapedRegExp = require('./src/regexp/autoEscapedRegExp.cjs.js');
10
- var isNode = require('./src/isNode.cjs.js');
11
- var index = require('./src/array/index.cjs.js');
12
- var sleep = require('./src/sleep.cjs.js');
13
- var intersection = require('./src/array/intersection.cjs.js');
14
- var union = require('./src/array/union.cjs.js');
15
- var difference = require('./src/array/difference.cjs.js');
16
- var symmetricDifference = require('./src/array/symmetricDifference.cjs.js');
17
-
18
-
19
-
20
- exports.createConstructor = createConstructor.createConstructor;
21
- exports.getRandomFloat = getRandomNumber.getRandomFloat;
22
- exports.getRandomInt = getRandomNumber.getRandomInt;
23
- exports.toLowerCamelCase = className.toLowerCamelCase;
24
- exports.toSplitCase = className.toSplitCase;
25
- exports.getRandomString = getRandomString.getRandomString;
26
- exports.debounce = performance.debounce;
27
- exports.throttle = performance.throttle;
28
- exports.escapeRegExp = escapeRegExp.escapeRegExp;
29
- exports.autoEscapedRegExp = autoEscapedRegExp.autoEscapedRegExp;
30
- exports.isBrowser = isNode.isBrowser;
31
- exports.isNode = isNode.isNode;
32
- exports.enArr = index.enArr;
33
- exports.sleep = sleep.sleep;
34
- exports.intersection = intersection.intersection;
35
- exports.union = union.union;
36
- exports.difference = difference.difference;
37
- exports.symmetricDifference = symmetricDifference.symmetricDifference;
3
+ var aTypeOfJs = require('a-type-of-js');
4
+
5
+ /**
6
+ *
7
+ * 构建一个 Constructor 构造函数
8
+ *
9
+ * 接收一个构造函数,然后返回 TS 能识别的构造函数自身
10
+ *
11
+ * 函数本身并没有执行任何逻辑,仅是简单的返回了实参自身
12
+ *
13
+ * 而经过该函数的包装,构造函数成了能够被 TS 识别为可用 new 实例的构造函数
14
+ *
15
+ * @param constructor - 传入一个构造函数
16
+ * @returns 返回传入的构造函数
17
+ *
18
+ * ```ts
19
+ * import { createConstructor } from "a-js-tools";
20
+ *
21
+ * type Tom = {
22
+ * a: number
23
+ * }
24
+ *
25
+ * function _Tom (this: TomType): Tom {
26
+ * this.a = 1;
27
+ *
28
+ * return this;
29
+ * }
30
+ *
31
+ * // 逻辑上没有错,但是会造成 ts 显示
32
+ * // 其目标缺少构造签名的 "new" 表达式隐式具有 "any" 类型。ts(7009)
33
+ * const a = new _Tom();
34
+ *
35
+ * const tomConstructor = createConstructor(_tom);
36
+ *
37
+ * const b = new tomConstructor(); // 这时就不会显示错误
38
+ *
39
+ * ```
40
+ *
41
+ */
42
+ function createConstructor(constructor) {
43
+ constructor.prototype.apply = Function.apply;
44
+ constructor.prototype.bind = Function.bind;
45
+ constructor.prototype.call = Function.call;
46
+ constructor.prototype.length = Function.length;
47
+ // constructor.prototype.arguments = Function.arguments;
48
+ constructor.prototype.name = Function.name;
49
+ constructor.prototype.toString = Function.toString;
50
+ return constructor;
51
+ }
52
+
53
+ /**
54
+ * 过去随机数
55
+ *
56
+ * @packageDocumentation
57
+ * @module @a-js-tools/get-random-number
58
+ * @license MIT
59
+ */
60
+ /**
61
+ *
62
+ * 获取一个随机的整数类型
63
+ *
64
+ * 您可以传入两个参数并获取它们之间的任意数字,返回值<span style="color:#ff0;">*会包含端值*</span>
65
+ *
66
+ * 如果只传递一个参数,则如果提供的值为负数,则得到一个小于(或大于)该数字的整数
67
+ *
68
+ * @param max 较大值 ,不允许为`NaN`
69
+ * @param min 较小值,不允许为 `NaN`
70
+ * @returns 任意的整数
71
+ */
72
+ function getRandomInt(max = 1, min = 0) {
73
+ // 判断是否为 NaN 或 不是数字
74
+ if (!isFinite(max) ||
75
+ !isFinite(min) ||
76
+ aTypeOfJs.isNaN(max) ||
77
+ aTypeOfJs.isNaN(min) ||
78
+ !aTypeOfJs.isNumber(max) ||
79
+ !aTypeOfJs.isNumber(min)) {
80
+ throw new TypeError('getRandomInt: max or min is NaN or is not a number');
81
+ }
82
+ /** 获取最小值 */
83
+ let _min = Math.ceil(Number(min)),
84
+ /** 获取最大值 */
85
+ _max = Math.floor(Number(max));
86
+ // 两值相等时,直接返回最大值
87
+ if (_max === _min)
88
+ return _max;
89
+ // 两值交换
90
+ if (_min > _max)
91
+ [_max, _min] = [_min, _max];
92
+ return Math.round(Math.random() * (_max - _min) + _min);
93
+ }
94
+ /**
95
+ *
96
+ * 获取任意的浮点数
97
+ *
98
+ * 您可以传入两个参数并获取它们之间的任意数字
99
+ *
100
+ * 如果只传入一个参数,则如果提供的值为负数,则获取小于(或大于)该数字的浮点数
101
+ *
102
+ * @param max 较大数,缺省值为 1
103
+ * @param min 较小值,缺省值为 0
104
+ * @returns 任意的浮点数
105
+ */
106
+ function getRandomFloat(max = 1, min = 0) {
107
+ // 判断是否为 NaN 或 不是数字
108
+ if (!isFinite(max) ||
109
+ !isFinite(min) ||
110
+ aTypeOfJs.isNaN(max) ||
111
+ aTypeOfJs.isNaN(min) ||
112
+ !aTypeOfJs.isNumber(max) ||
113
+ !aTypeOfJs.isNumber(min)) {
114
+ throw new TypeError('getRandomInt: max or min is NaN or is not a number');
115
+ }
116
+ if (max == min)
117
+ max++;
118
+ if (min > max)
119
+ [max, min] = [min, max];
120
+ return Math.random() * (max - min) + min;
121
+ }
122
+
123
+ /**
124
+ * 驼峰命名与连字符命名法的互换
125
+ *
126
+ * @packageDocumentation
127
+ * @module @a-js-tools/class-name
128
+ * @license MIT
129
+ */
130
+ /**
131
+ *
132
+ * 连字符连接转化为小/大驼峰命名法
133
+ *
134
+ * @param str 待转化文本
135
+ * @param dividingType 连字符,缺省值为 "-"
136
+ * @param initial 是否转换第一个字符。默认值为 false (小驼峰类型)
137
+ * @returns 驼峰命名法字符串(e.g. “helloWorld”)
138
+ *
139
+ */
140
+ function toLowerCamelCase(
141
+ /** 待转化文本 */
142
+ str,
143
+ /** 连字符,缺省值为 "-" */
144
+ dividingType = '-',
145
+ /** 是否转换第一个字符。默认值为 false (小驼峰类型) */
146
+ initial = false) {
147
+ let result = str;
148
+ /**
149
+ * 匹配规则
150
+ *
151
+ * - 匹配到分隔符,将分隔符后面的字符转化为大写
152
+ */
153
+ const template = /[\\]|[\^]|[?]|[-]|[.]|[(]|[)]|[|]|[[]\[\]]|[{]|[}]|[+]|[*]|[$]/;
154
+ /** 转化首字符 */
155
+ const toTransform = (_str, _dividingType) => _str.replace(new RegExp(`${template.test(_dividingType) ? `\\${_dividingType}` : _dividingType}([a-zA-Z])`, 'g'), (match, p1) => p1.toUpperCase());
156
+ // 多分隔符转化
157
+ dividingType
158
+ .split('')
159
+ .forEach((item) => (result = toTransform(result, item)));
160
+ return initial
161
+ ? result.replace(/^./, (match) => match.toUpperCase())
162
+ : result;
163
+ }
164
+ /**
165
+ * 驼峰命名法转化为连字符连接
166
+ *
167
+ * @param str 待转化文本
168
+ * @param dividingType 分割符
169
+ * @returns 分割符转化的文本 (e.g. 'hello-world')
170
+ *
171
+ */
172
+ function toSplitCase(str, dividingType = '-') {
173
+ const result = str.replace(/[A-Z]/g, (match) => dividingType.concat(match.toLowerCase()));
174
+ return result.startsWith(dividingType) ? result.substring(1) : result;
175
+ }
176
+
177
+ /**
178
+ * 获取随机字符串
179
+ *
180
+ * @packageDocumentation
181
+ * @module @a-js-tools/get-random-string
182
+ * @license MIT
183
+ */
184
+ /**
185
+ *
186
+ * 获取简单的随机字符串
187
+ *
188
+ * @param options - 字符串长度
189
+ * @returns - 随机字符串
190
+ *
191
+ *
192
+ */
193
+ function getRandomString(options) {
194
+ // 验证输入参数
195
+ if (
196
+ // 参数类型错误
197
+ (!aTypeOfJs.isPlainObject(options) && !aTypeOfJs.isNumber(options)) ||
198
+ // 参数为 NaN
199
+ (aTypeOfJs.isNumber(options) && aTypeOfJs.isNaN(options)) ||
200
+ // 参数为数字时为无穷大
201
+ (aTypeOfJs.isNumber(options) && !isFinite(options)) ||
202
+ // 参数为数字时为非整数
203
+ (aTypeOfJs.isNumber(options) && !Number.isInteger(options)) ||
204
+ // 参数为数字时为负数
205
+ (aTypeOfJs.isNumber(options) && Number.isInteger(options) && options < 1) ||
206
+ // 参数为数值然而却小于 1
207
+ (aTypeOfJs.isNumber(options) && options < 1) ||
208
+ // 参数为对象但是 length 属性非数值
209
+ (aTypeOfJs.isPlainObject(options) &&
210
+ (!aTypeOfJs.isNumber(options.length) ||
211
+ options.length < 1 ||
212
+ !Number.isInteger(options.length))))
213
+ throw new TypeError('参数类型错误 ❌ (getRandomString)');
214
+ const initOptions = {
215
+ length: 32,
216
+ chars: 'abcdefghijklmnopqrstuvwxyz',
217
+ chars2: '0123456789',
218
+ chars3: '!@#$%^&*()_+~`|}{[]:;?><,./-=',
219
+ type: 'string',
220
+ includeUppercaseLetters: false,
221
+ includeNumbers: false,
222
+ includeSpecial: false,
223
+ };
224
+ /// 生成 UUID
225
+ if (initOptions.type === 'uuid')
226
+ return crypto.randomUUID();
227
+ // 验证输入参数
228
+ if (aTypeOfJs.isNumber(options) && Number.isInteger(options) && options > 0)
229
+ Object.assign(initOptions, { length: options });
230
+ if (aTypeOfJs.isPlainObject(options)) {
231
+ Object.assign(initOptions, options);
232
+ initOptions.length = initOptions.length < 1 ? 32 : initOptions.length;
233
+ }
234
+ /** 生成随机字符串 */
235
+ const templateCharsArr = initOptions.chars.split('');
236
+ // 添加大写字母
237
+ if (initOptions.includeUppercaseLetters)
238
+ interleaveString(templateCharsArr, initOptions.chars.toUpperCase());
239
+ // 添加数字
240
+ if (initOptions.includeNumbers)
241
+ interleaveString(templateCharsArr, initOptions.chars2);
242
+ // 添加特殊字符
243
+ if (initOptions.includeSpecial)
244
+ interleaveString(templateCharsArr, initOptions.chars3);
245
+ // 使用密码学安全的随机数生成器
246
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(initOptions.length));
247
+ let result = '';
248
+ /** 获取最后的 chars 数据 */
249
+ const chars = templateCharsArr.join('');
250
+ // 循环遍历
251
+ bytes.forEach(byte => (result += chars.charAt(byte % chars.length)));
252
+ /**
253
+ *
254
+ * 字符串交叉函数
255
+ *
256
+ * 非线形串交叉,对相交叉
257
+ *
258
+ * @param str1 - 字符串1
259
+ * @param str2 - 字符串2
260
+ * @returns - 交叉后的字符串
261
+ * @example
262
+ * ```ts
263
+ * interleaveString('abc', '123') // 'a1b2c3'
264
+ * ```
265
+ */
266
+ function interleaveString(str1, str2) {
267
+ const str1Length = str1.length, str2Length = str2.length;
268
+ const maxLength = Math.max(str1Length, str2Length);
269
+ for (let i = 0; i < maxLength; i++) {
270
+ if (i < str1Length && !aTypeOfJs.isUndefined(str2[i]))
271
+ str1[i] += str2[i];
272
+ else if (i < str2Length)
273
+ str1[i] = str2[i];
274
+ }
275
+ }
276
+ return result;
277
+ }
278
+
279
+ /**
280
+ * 防抖和节流
281
+ *
282
+ * @packageDocumentation
283
+ * @module @a-js-tools/performance
284
+ * @license MIT
285
+ */
286
+ /**
287
+ *
288
+ * 防抖
289
+ *
290
+ * @param callback 回调函数
291
+ * @param options 延迟时间(毫秒),默认 200 (ms) 或包含 this 的配置
292
+ * @returns 返回的闭包函数
293
+ * @example
294
+ *
295
+ * ```ts
296
+ * const debounce = (callback: Function, delay = 300) => {
297
+ * let timer: any = null
298
+ * return (...args: any[]) => {
299
+ * clearTimeout(timer)
300
+ * }
301
+ * }
302
+ *
303
+ */
304
+ function debounce(callback, options = 200) {
305
+ if (!aTypeOfJs.isFunction(callback))
306
+ throw new TypeError('callback must be a function');
307
+ if (aTypeOfJs.isNumber(options))
308
+ options = {
309
+ delay: options,
310
+ this: null,
311
+ };
312
+ if (aTypeOfJs.isUndefined(options.delay) ||
313
+ !isFinite(options.delay) ||
314
+ options.delay < 0)
315
+ // 强制转换非数值
316
+ options.delay = 200;
317
+ /** 定时器返回的 id */
318
+ let timeoutId;
319
+ const clear = () => {
320
+ if (timeoutId) {
321
+ clearTimeout(timeoutId);
322
+ timeoutId = undefined;
323
+ }
324
+ };
325
+ const result = (...args) => {
326
+ clear();
327
+ timeoutId = setTimeout(() => {
328
+ try {
329
+ Reflect.apply(callback, options?.this ?? null, args);
330
+ }
331
+ catch (error) {
332
+ console.log('Debounce callback throw an error', error);
333
+ }
334
+ }, Math.max(options?.delay ?? 5, 5));
335
+ };
336
+ result.cancel = () => clear();
337
+ return result;
338
+ }
339
+ /**
340
+ * 节流
341
+ *
342
+ * @param callback 回调函数
343
+ * @param options 延迟时间(毫秒),默认 200 (ms) 或设置 this
344
+ * @returns 返回的闭包函数
345
+ */
346
+ function throttle(callback, options = 200) {
347
+ if (!aTypeOfJs.isFunction(callback))
348
+ throw new TypeError('callback must be a function');
349
+ if (aTypeOfJs.isNumber(options))
350
+ options = {
351
+ delay: options,
352
+ this: null,
353
+ };
354
+ if (aTypeOfJs.isUndefined(options.delay) ||
355
+ !isFinite(options.delay) ||
356
+ options.delay < 0)
357
+ // 强制转换非数值
358
+ options.delay = 200;
359
+ /** 延迟控制插销 */
360
+ let inThrottle = false;
361
+ /** 延迟控制 */
362
+ let timeoutId = null;
363
+ const throttled = (...args) => {
364
+ if (inThrottle)
365
+ return;
366
+ try {
367
+ Reflect.apply(callback, options?.this ?? null, args);
368
+ }
369
+ catch (error) {
370
+ console.error('Throttle 执行回调抛出问题', error);
371
+ }
372
+ inThrottle = true;
373
+ if (!aTypeOfJs.isNull(timeoutId))
374
+ clearTimeout(timeoutId);
375
+ timeoutId = setTimeout(() => {
376
+ inThrottle = false;
377
+ timeoutId = null;
378
+ }, Math.max(options?.delay ?? 5, 5));
379
+ };
380
+ throttled.cancel = () => {
381
+ if (!aTypeOfJs.isNull(timeoutId))
382
+ clearTimeout(timeoutId);
383
+ inThrottle = false;
384
+ timeoutId = null;
385
+ };
386
+ return throttled;
387
+ }
388
+
389
+ /**
390
+ *
391
+ * 将一个字符串转化为符合正则要求的字符串
392
+ *
393
+ * @param str 需要转义的字符串
394
+ * @requires escapeRegExp 转化后字符串
395
+ * @example
396
+ *
397
+ * ```ts
398
+ * import { escapeRegExp } from 'a-js-tools';
399
+ *
400
+ * escapeRegExp('a.b.c'); // 'a\\.b\\.c'
401
+ * escapeRegExp('a\\.b\\.c'); // 'a\\\\.b\\\\.c'
402
+ * escapeRegExp('[a-z]'); // '\\[a-z\\]'
403
+ * escapeRegExp('^abc$'); // '\\^abc\\$'
404
+ * ```
405
+ */
406
+ function escapeRegExp(str) {
407
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
408
+ }
409
+
410
+ /**
411
+ *
412
+ * 解析 options
413
+ *
414
+ */
415
+ function parse(options) {
416
+ // 处理 options
417
+ if (aTypeOfJs.isString(options)) {
418
+ options = {
419
+ flags: options,
420
+ };
421
+ }
422
+ // 处理 flags
423
+ if (!aTypeOfJs.isString(options.flags))
424
+ options.flags = '';
425
+ else {
426
+ // 需求是保留字符串中的某一部分,使用
427
+ const regexp = /[migsuy]/g;
428
+ const matchResult = options.flags.match(regexp);
429
+ if (aTypeOfJs.isNull(matchResult))
430
+ options.flags = '';
431
+ else
432
+ options.flags = [...new Set(matchResult)].join('');
433
+ }
434
+ return options;
435
+ }
436
+
437
+ /**
438
+ *
439
+ * ## 适用于简单的文本字符串自动转化为简单模式正则表达式
440
+ *
441
+ * *若字符串包含且需保留字符类、组、反向引用、量词等时,该方法可能不适用*
442
+ *
443
+ * @param pattern 待转化的文本字符串
444
+ * @param options 转化选项。 为文本字符串时,默认为正则表达式的标志,还可指定是否匹配开头或结尾
445
+ * @returns 正则表达式
446
+ * @example
447
+ *
448
+ * ```ts
449
+ * import { autoEscapedRegExp } from 'a-regexp';
450
+ *
451
+ * autoEscapedRegExp('abc'); // => /abc/
452
+ * autoEscapedRegExp('abc', 'gim'); // => /abc/gim
453
+ * autoEscapedRegExp('abc', { flags: 'g', start: true }); // => /^abc/g
454
+ * autoEscapedRegExp('abc', { flags: 'g', end: true }); // => /abc$/g
455
+ * autoEscapedRegExp('abc', { start: true, end: true }); // => /^abc$/
456
+ *
457
+ * // 转化特殊字符类、组、反向引用、量词等
458
+ * // 无法保留匹配规则
459
+ * autoEscapedRegExp('a-zA-Z0-9'); // => /a-zA-Z0-9/
460
+ * autoEscapedRegExp('a-zA-Z0-9', 'g'); // => /a-zA-Z0-9/g
461
+ * autoEscapedRegExp('[a-zA-Z0-9]'); // => /\[a-zA-Z0-9\]/
462
+ * autoEscapedRegExp('^[a-zA-Z0-9]+$'); // => /\^\[a-zA-Z0-9\]\$/
463
+ *
464
+ * ```
465
+ *
466
+ */
467
+ function autoEscapedRegExp(pattern, options) {
468
+ if (!aTypeOfJs.isString(pattern))
469
+ throw new TypeError('pattern must be a 字符串');
470
+ pattern = escapeRegExp(pattern);
471
+ /** 简单转化 */
472
+ if (aTypeOfJs.isUndefined(options))
473
+ return new RegExp(pattern);
474
+ options = parse(options);
475
+ return new RegExp(`${options.start ? '^' : ''}${pattern}${options.end ? '$' : ''}`, options.flags);
476
+ }
477
+
478
+ /**
479
+ *
480
+ * 判断当前环境是否为 node 环境
481
+ *
482
+ */
483
+ function isNode() {
484
+ return !aTypeOfJs.isUndefined(globalThis?.process?.versions?.node);
485
+ }
486
+ /**
487
+ *
488
+ * 是否为浏览器环境
489
+ *
490
+ */
491
+ function isBrowser() {
492
+ return !isNode();
493
+ }
494
+
495
+ /**
496
+ *
497
+ * 两个数组的交集
498
+ *
499
+ * @param a 数组 1️⃣
500
+ * @param b 数组 2️⃣
501
+ * @returns 返回两个数组的交集
502
+ * @example
503
+ *
504
+ * ```ts
505
+ * import { intersection } from 'a-js-tools';
506
+ *
507
+ * const log = console.log;
508
+ *
509
+ *
510
+ * log(intersection([1, 2, 3, 4], [2, 3])); // [2, 3]
511
+ * log(intersection([1, 3, 5, 7], [2, 3, 4])); // [3]
512
+ *
513
+ * ```
514
+ *
515
+ */
516
+ function intersection(a, b) {
517
+ if (!aTypeOfJs.isArray(a) || !aTypeOfJs.isArray(b))
518
+ throw new TypeError('参数必须是数组类型数据');
519
+ // 任意数组为空,则返回空数组
520
+ if (aTypeOfJs.isEmptyArray(a) || aTypeOfJs.isEmptyArray(b))
521
+ return [];
522
+ /**
523
+ * 在实际运算中, new Set() 的 开销为 O(n) ,filter 的开销也为 O(n)
524
+ *
525
+ * 但是以较短的数组创建 Set ,可以节省内存开销
526
+ */
527
+ const [shorter, longer] = a.length <= b.length ? [a, b] : [b, a];
528
+ // 提前创建工具 Set
529
+ const shortSet = new Set(shorter);
530
+ return longer.filter(item => shortSet.has(item));
531
+ }
532
+
533
+ /**
534
+ *
535
+ * 数组的并集
536
+ *
537
+ * <span style="color:#f36;">请注意,参数有不为数组时直接抛出 TypeError</span>
538
+ * @param arrays - 多个数组
539
+ * @returns 联合后的数组
540
+ *
541
+ *
542
+ * @example
543
+ *
544
+ * ```ts
545
+ * import { union } from 'a-js-tools';
546
+ *
547
+ * const log = console.log;
548
+ *
549
+ * // []
550
+ * log(union());
551
+ *
552
+ * // [1, 2, 3]
553
+ * log(union([1, 2, 3]));
554
+ *
555
+ * // TypeError
556
+ * log(union([1, 2, 3], 'i'));
557
+ * log(union([1, 2, 3], undefined));
558
+ * log(union([1, 2, 3], null));
559
+ * log(union([1, 2, 3], 4));
560
+ * log(union([1, 2, 3], {}));
561
+ * log(union([1, 2, 3], false));
562
+ *
563
+ * // [1, 2, 3, 4, 6]
564
+ * log(union([1, 2, 3], [2, 4, 6]));
565
+ *
566
+ * // [1, 2, 3, 4, 6]
567
+ * log(union([1, 2, 3], [2, 4, 6], [1, 2, 3]));
568
+ *
569
+ * // [1, 2, 3, 4, 6]
570
+ * log(union([1, 2, 3], [2, 4, 6], [1, 2, 3], [1, 2, 3]));
571
+ * ```
572
+ *
573
+ */
574
+ function union(...arrays) {
575
+ if (aTypeOfJs.isEmptyArray(arrays))
576
+ return [];
577
+ if (arrays.some(i => !aTypeOfJs.isArray(i)))
578
+ throw new TypeError('参数必须都是数组形式的元素');
579
+ if (arrays.length === 1)
580
+ return [...arrays[0]];
581
+ const resultSet = new Set();
582
+ for (const array of arrays) {
583
+ for (const item of array)
584
+ resultSet.add(item);
585
+ }
586
+ return Array.from(resultSet);
587
+ }
588
+
589
+ /**
590
+ * 求给出的两个数组的差值(A - B)
591
+ *
592
+ * @param a - 第一个数组
593
+ * @param b - 第二个数组
594
+ * @throws {TypeError} 当两个参数有一个不是
595
+ * @description 当两个参数有一个不是数组时将抛出
596
+ * @returns 返回第一个参数相对第二个参数的差值
597
+ * @example
598
+ *
599
+ * ```ts
600
+ * import { difference} from 'a-js-tools';
601
+ *
602
+ * const log = console.log;
603
+ *
604
+ *
605
+ * log(difference([], [1, 2, 3])); // []
606
+ *
607
+ * log([1, 2, 3], []); //[1, 2, 3]
608
+ *
609
+ * log([1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5]); //[6, 7]
610
+ *
611
+ * // 将抛出 TypeError
612
+ * log(difference([1, 2, 3], 'a'));
613
+ * log(difference([1, 2, 3], 1));
614
+ * log(difference([1, 2, 3], undefined));
615
+ * log(difference([1, 2, 3], null));
616
+ * log(difference([1, 2, 3], true));
617
+ * ```
618
+ *
619
+ */
620
+ function difference(a, b) {
621
+ if (!aTypeOfJs.isArray(a) || !aTypeOfJs.isArray(b))
622
+ throw new TypeError('参数需为数组');
623
+ if (aTypeOfJs.isEmptyArray(a) || aTypeOfJs.isEmptyArray(b))
624
+ return a;
625
+ /** 获取两个数组中长度较小的 */
626
+ // 参数有顺序要求
627
+ // const [shorter, longer] = a.length > b.length ? [b, a] : [a, b];
628
+ // const shorterSet = new Set(shorter);
629
+ const bSet = new Set(b);
630
+ return a.filter(i => !bSet.has(i));
631
+ }
632
+
633
+ /**
634
+ *
635
+ * 对称差集 ( A △ B)
636
+ *
637
+ * @param a - 数组 a
638
+ * @param b - 数组 b
639
+ * @returns - 返回一个全新的数组
640
+ *
641
+ * @example
642
+ *
643
+ * ```ts
644
+ * import { symmetricDifference } from 'a-js-tools';
645
+ *
646
+ * const log = console.log;
647
+ *
648
+ * log(symmetricDifference([1, 2], [2, 3])); // [1, 3]
649
+ *
650
+ * log(symmetricDifference([1, 2, 3], [1, 2, 4])); // [3, 4]
651
+ *
652
+ * log(symmetricDifference([1, 2, 3], [1, 2, 3])); // []
653
+ *
654
+ *
655
+ * /// TypeError
656
+ * log(symmetricDifference(1, []));
657
+ * log(symmetricDifference(undefined, []));
658
+ * log(symmetricDifference(null, []));
659
+ * log(symmetricDifference('a', []));
660
+ * log(symmetricDifference(true, []));
661
+ *
662
+ * ```
663
+ *
664
+ */
665
+ function symmetricDifference(a, b) {
666
+ if (!aTypeOfJs.isArray(a) || !aTypeOfJs.isArray(b))
667
+ throw new TypeError('参数必须是数组');
668
+ if (aTypeOfJs.isEmptyArray(a))
669
+ return [...b];
670
+ if (aTypeOfJs.isEmptyArray(b))
671
+ return [...a];
672
+ return [...difference(a, b), ...difference(b, a)];
673
+ }
674
+
675
+ /**
676
+ *
677
+ * 数组的一些方法
678
+ *
679
+ * - union 两个数组的并集(排除共有项)
680
+ * - intersection 两个数组的交集(共有项)
681
+ * - difference 两个数组的差集 (A - B)
682
+ * - symmetricDifference 对称差集 ( A △ B)
683
+ *
684
+ */
685
+ const enArr = {
686
+ /**
687
+ *
688
+ * 数组的并集
689
+ *
690
+ * <span style="color:#f36;">请注意,参数有不为数组时直接抛出 TypeError</span>
691
+ * @param arrays - 多个数组
692
+ * @returns 联合后的数组
693
+ *
694
+ *
695
+ * @example
696
+ *
697
+ * ```ts
698
+ * import { union } from 'a-js-tools';
699
+ *
700
+ * const log = console.log;
701
+ *
702
+ * // []
703
+ * log(union());
704
+ *
705
+ * // [1, 2, 3]
706
+ * log(union([1, 2, 3]));
707
+ *
708
+ * // TypeError
709
+ * log(union([1, 2, 3], 'i'));
710
+ * log(union([1, 2, 3], undefined));
711
+ * log(union([1, 2, 3], null));
712
+ * log(union([1, 2, 3], 4));
713
+ * log(union([1, 2, 3], {}));
714
+ * log(union([1, 2, 3], false));
715
+ *
716
+ * // [1, 2, 3, 4, 6]
717
+ * log(union([1, 2, 3], [2, 4, 6]));
718
+ *
719
+ * // [1, 2, 3, 4, 6]
720
+ * log(union([1, 2, 3], [2, 4, 6], [1, 2, 3]));
721
+ *
722
+ * // [1, 2, 3, 4, 6]
723
+ * log(union([1, 2, 3], [2, 4, 6], [1, 2, 3], [1, 2, 3]));
724
+ * ```
725
+ *
726
+ */
727
+ union,
728
+ /**
729
+ *
730
+ * 两个数组的交集
731
+ *
732
+ * @param a 数组 1️⃣
733
+ * @param b 数组 2️⃣
734
+ * @returns 返回两个数组的交集
735
+ * @example
736
+ *
737
+ * ```ts
738
+ * import { intersection } from 'a-js-tools';
739
+ *
740
+ * const log = console.log;
741
+ *
742
+ *
743
+ * log(intersection([1, 2, 3, 4], [2, 3])); // [2, 3]
744
+ * log(intersection([1, 3, 5, 7], [2, 3, 4])); // [3]
745
+ *
746
+ * ```
747
+ *
748
+ */
749
+ intersection,
750
+ /**
751
+ * 求给出的两个数组的差值(A - B)
752
+ *
753
+ * @param a - 第一个数组
754
+ * @param b - 第二个数组
755
+ * @throws {TypeError} 当两个参数有一个不是
756
+ * @description 当两个参数有一个不是数组时将抛出
757
+ * @returns 返回第一个参数相对第二个参数的差值
758
+ * @example
759
+ *
760
+ * ```ts
761
+ * import { difference} from 'a-js-tools';
762
+ *
763
+ * const log = console.log;
764
+ *
765
+ *
766
+ * log(difference([], [1, 2, 3])); // []
767
+ *
768
+ * log([1, 2, 3], []); //[1, 2, 3]
769
+ *
770
+ * log([1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5]); //[6, 7]
771
+ *
772
+ * // 将抛出 TypeError
773
+ * log(difference([1, 2, 3], 'a'));
774
+ * log(difference([1, 2, 3], 1));
775
+ * log(difference([1, 2, 3], undefined));
776
+ * log(difference([1, 2, 3], null));
777
+ * log(difference([1, 2, 3], true));
778
+ * ```
779
+ *
780
+ */
781
+ difference,
782
+ /**
783
+ *
784
+ * 对称差集 ( A △ B)
785
+ *
786
+ * @param a - 数组 a
787
+ * @param b - 数组 b
788
+ * @returns - 返回一个全新的数组
789
+ *
790
+ * @example
791
+ *
792
+ * ```ts
793
+ * import { symmetricDifference } from 'a-js-tools';
794
+ *
795
+ * const log = console.log;
796
+ *
797
+ * log(symmetricDifference([1, 2], [2, 3])); // [1, 3]
798
+ *
799
+ * log(symmetricDifference([1, 2, 3], [1, 2, 4])); // [3, 4]
800
+ *
801
+ * log(symmetricDifference([1, 2, 3], [1, 2, 3])); // []
802
+ *
803
+ *
804
+ * /// TypeError
805
+ * log(symmetricDifference(1, []));
806
+ * log(symmetricDifference(undefined, []));
807
+ * log(symmetricDifference(null, []));
808
+ * log(symmetricDifference('a', []));
809
+ * log(symmetricDifference(true, []));
810
+ *
811
+ * ```
812
+ *
813
+ */
814
+ symmetricDifference,
815
+ };
816
+
817
+ /**
818
+ *
819
+ * ## 线程休息
820
+ *
821
+ * 但从调用到执行完毕总是与期望的时间并不相吻合,除非执行是线型的(也不保证时间的严格性)
822
+ *
823
+ * - 宏任务:整体代码、setTimeout、DOM 事件回调、requestAnimationFrame、setImmediate、setInterval、I/O操作、UI渲染等
824
+ * - 微任务:Promise的then/catch/finally、process.nextTick(Node.js)、MutationObserver、queueMicrotask(显示添加微任务)等
825
+ *
826
+ * <span style="color:#ff0;">*Node.js中的process.nextTick优先级高于其他微任务*</span>
827
+ *
828
+ * @param delay 睡觉时长(机器时间,毫秒为单位)
829
+ * @returns 🈳
830
+ * @example
831
+ *
832
+ * ```ts
833
+ * import { sleep } from 'a-js-tools';
834
+ *
835
+ * console.log(Date.now()); // 1748058118471
836
+ * await sleep(1000);
837
+ * console.log(Date.now()); // 1748058119473
838
+ *
839
+ * ```
840
+ *
841
+ */
842
+ async function sleep(delay = 1000) {
843
+ if (!isFinite(delay) || delay < 0)
844
+ throw new TypeError('delay 应该是一个正常的数值');
845
+ if (aTypeOfJs.isZero(delay))
846
+ return Promise.resolve();
847
+ return new Promise(resolve => setTimeout(resolve, delay));
848
+ }
849
+
850
+ exports.autoEscapedRegExp = autoEscapedRegExp;
851
+ exports.createConstructor = createConstructor;
852
+ exports.debounce = debounce;
853
+ exports.difference = difference;
854
+ exports.enArr = enArr;
855
+ exports.escapeRegExp = escapeRegExp;
856
+ exports.getRandomFloat = getRandomFloat;
857
+ exports.getRandomInt = getRandomInt;
858
+ exports.getRandomString = getRandomString;
859
+ exports.intersection = intersection;
860
+ exports.isBrowser = isBrowser;
861
+ exports.isNode = isNode;
862
+ exports.sleep = sleep;
863
+ exports.symmetricDifference = symmetricDifference;
864
+ exports.throttle = throttle;
865
+ exports.toLowerCamelCase = toLowerCamelCase;
866
+ exports.toSplitCase = toSplitCase;
867
+ exports.union = union;