@pawover/kit 0.0.0-beta.3 → 0.0.0-beta.30

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.
@@ -0,0 +1,2037 @@
1
+ //#region src/utils/typeof/types.ts
2
+ const PROTOTYPE_TAGS = {
3
+ abortSignal: "[object AbortSignal]",
4
+ array: "[object Array]",
5
+ asyncFunction: "[object AsyncFunction]",
6
+ asyncGeneratorFunction: "[object AsyncGeneratorFunction]",
7
+ bigInt: "[object BigInt]",
8
+ blob: "[object Blob]",
9
+ boolean: "[object Boolean]",
10
+ date: "[object Date]",
11
+ error: "[object Error]",
12
+ file: "[object File]",
13
+ function: "[object Function]",
14
+ generatorFunction: "[object GeneratorFunction]",
15
+ iframe: "[object HTMLIFrameElement]",
16
+ map: "[object Map]",
17
+ null: "[object Null]",
18
+ number: "[object Number]",
19
+ object: "[object Object]",
20
+ promise: "[object Promise]",
21
+ readableStream: "[object ReadableStream]",
22
+ regExp: "[object RegExp]",
23
+ set: "[object Set]",
24
+ string: "[object String]",
25
+ symbol: "[object Symbol]",
26
+ undefined: "[object Undefined]",
27
+ URLSearchParams: "[object URLSearchParams]",
28
+ weakMap: "[object WeakMap]",
29
+ weakSet: "[object WeakSet]",
30
+ webSocket: "[object WebSocket]",
31
+ window: "[object Window]"
32
+ };
33
+ const TYPED_ARRAY_TAGS = new Set([
34
+ "[object Int8Array]",
35
+ "[object Uint8Array]",
36
+ "[object Uint8ClampedArray]",
37
+ "[object Int16Array]",
38
+ "[object Uint16Array]",
39
+ "[object Int32Array]",
40
+ "[object Uint32Array]",
41
+ "[object Float32Array]",
42
+ "[object Float64Array]",
43
+ "[object BigInt64Array]",
44
+ "[object BigUint64Array]"
45
+ ]);
46
+ function resolvePrototypeString(value) {
47
+ return Object.prototype.toString.call(value);
48
+ }
49
+
50
+ //#endregion
51
+ //#region src/utils/typeof/isAbortSignal.ts
52
+ /**
53
+ * 检查 value 是否为 AbortSignal
54
+ * @param value 待检查值
55
+ * @returns 是否为 AbortSignal
56
+ */
57
+ function isAbortSignal(value) {
58
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.abortSignal;
59
+ }
60
+
61
+ //#endregion
62
+ //#region src/utils/typeof/isArray.ts
63
+ /**
64
+ * 检查 value 是否为数组
65
+ *
66
+ * @param value 待检查值
67
+ * @returns 是否为数组
68
+ * @example
69
+ * ```ts
70
+ * isArray([]); // true
71
+ * ```
72
+ */
73
+ function isArray(value) {
74
+ return Array.isArray(value);
75
+ }
76
+ /**
77
+ * 检查 value 是否为 TypedArray
78
+ *
79
+ * @param value 待检查值
80
+ * @returns 是否为 TypedArray
81
+ * @example
82
+ * ```ts
83
+ * isTypedArray(new Int8Array()); // true
84
+ * ```
85
+ */
86
+ function isTypedArray(value) {
87
+ return typeof value === "object" && value !== null && TYPED_ARRAY_TAGS.has(resolvePrototypeString(value));
88
+ }
89
+
90
+ //#endregion
91
+ //#region src/utils/typeof/isBigInt.ts
92
+ /**
93
+ * 检查 value 是否为 BigInt
94
+ * @param value 待检查值
95
+ * @returns 是否为 BigInt
96
+ */
97
+ function isBigInt(value) {
98
+ return typeof value === "bigint";
99
+ }
100
+
101
+ //#endregion
102
+ //#region src/utils/typeof/isBlob.ts
103
+ /**
104
+ * 检查 value 是否为 Blob
105
+ * @param value 待检查值
106
+ * @returns 是否为 Blob
107
+ */
108
+ function isBlob(value) {
109
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.blob;
110
+ }
111
+ function isFile(value) {
112
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.file;
113
+ }
114
+
115
+ //#endregion
116
+ //#region src/utils/typeof/isBoolean.ts
117
+ /**
118
+ * 检查 value 是否为 Boolean
119
+ * @param value 待检查值
120
+ * @returns 是否为 Boolean
121
+ */
122
+ function isBoolean(value) {
123
+ return typeof value === "boolean";
124
+ }
125
+
126
+ //#endregion
127
+ //#region src/utils/typeof/isFunction.ts
128
+ /**
129
+ * 检查 value 是否为 Function
130
+ * @param value 待检查值
131
+ * @returns 是否为 Function
132
+ */
133
+ function isFunction(value) {
134
+ return typeof value === "function";
135
+ }
136
+ /**
137
+ * 检查 value 是否为 AsyncFunction
138
+ * @param value 待检查值
139
+ * @returns 是否为 AsyncFunction
140
+ */
141
+ function isAsyncFunction(value) {
142
+ return isFunction(value) && resolvePrototypeString(value) === PROTOTYPE_TAGS.asyncFunction;
143
+ }
144
+ /**
145
+ * 检查 value 是否为 GeneratorFunction
146
+ * @param value 待检查值
147
+ * @returns 是否为 GeneratorFunction
148
+ */
149
+ function isGeneratorFunction(value) {
150
+ return isFunction(value) && resolvePrototypeString(value) === PROTOTYPE_TAGS.generatorFunction;
151
+ }
152
+ /**
153
+ * 检查 value 是否为 AsyncGeneratorFunction
154
+ * @param value 待检查值
155
+ * @returns 是否为 AsyncGeneratorFunction
156
+ */
157
+ function isAsyncGeneratorFunction(value) {
158
+ return isFunction(value) && resolvePrototypeString(value) === PROTOTYPE_TAGS.asyncGeneratorFunction;
159
+ }
160
+
161
+ //#endregion
162
+ //#region src/utils/typeof/isClass.ts
163
+ function isConstructable(fn) {
164
+ try {
165
+ Reflect.construct(fn, []);
166
+ return true;
167
+ } catch {
168
+ return false;
169
+ }
170
+ }
171
+ /**
172
+ * 检查 value 是否为 Class
173
+ *
174
+ * @param value 待检查值
175
+ * @returns 是否为 Class
176
+ * @example
177
+ * ```ts
178
+ * class A {}
179
+ * isClass(A); // true
180
+ * isClass(() => {}); // false
181
+ * ```
182
+ */
183
+ function isClass(value) {
184
+ return isFunction(value) && !isAsyncFunction(value) && Function.prototype.toString.call(value).startsWith("class ") && isConstructable(value) && value.prototype !== void 0;
185
+ }
186
+
187
+ //#endregion
188
+ //#region src/utils/typeof/isDate.ts
189
+ /**
190
+ * 检查 value 是否为 Date 对象
191
+ *
192
+ * @param value 待检查值
193
+ * @param invalidCheck 是否要求日期有效(非 Invalid Date)。默认 true
194
+ * - true: 仅当是有效 Date 对象时返回 true(排除 new Date('invalid'))
195
+ * - false: 只要 [[Prototype]] 是 Date 即返回 true(包含 Invalid Date)
196
+ * @returns 是否为 Date 对象,根据 invalidCheck 返回不同语义的 Date 判定
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * isDate(new Date()); // true
201
+ * isDate(new Date('invalid')); // false
202
+ * isDate(new Date('invalid'), false); // true
203
+ * isDate(null); // false
204
+ * isDate({}); // false
205
+ * ```
206
+ */
207
+ function isDate(value, invalidCheck = true) {
208
+ if (!value || typeof value !== "object") return false;
209
+ if (resolvePrototypeString(value) !== PROTOTYPE_TAGS.date) return false;
210
+ if (!invalidCheck) return true;
211
+ try {
212
+ const time = value.getTime();
213
+ return typeof time === "number" && !Number.isNaN(time);
214
+ } catch {
215
+ return false;
216
+ }
217
+ }
218
+
219
+ //#endregion
220
+ //#region src/utils/typeof/isEnumeration.ts
221
+ /**
222
+ * 判断一个值是否为有效的枚举
223
+ * - 枚举不能为空
224
+ * - 枚举所有的值必须是 string 或 number
225
+ *
226
+ * @param enumeration 待检查值
227
+ * @returns 是否为有效的枚举
228
+ */
229
+ function isEnumeration(enumeration) {
230
+ if (!isObject(enumeration)) return [false, false];
231
+ const keys = Object.keys(enumeration);
232
+ if (!keys.length) return [false, false];
233
+ const values = Object.values(enumeration);
234
+ if (!values.every((v) => typeof v === "string" || typeof v === "number")) return [false, false];
235
+ return [true, keys.every((k) => values.some((v) => v.toString() === k))];
236
+ }
237
+
238
+ //#endregion
239
+ //#region src/utils/typeof/isEqual.ts
240
+ /**
241
+ * 深度比较两个值是否相等
242
+ *
243
+ * @param value 待比较值 A
244
+ * @param other 待比较值 B
245
+ * @returns 是否相等
246
+ * @example
247
+ * ```ts
248
+ * isEqual({ a: 1 }, { a: 1 }); // true
249
+ * ```
250
+ */
251
+ function isEqual(x, y) {
252
+ if (Object.is(x, y)) return true;
253
+ if (isDate(x) && isDate(y)) return x.getTime() === y.getTime();
254
+ if (isRegExp(x) && isRegExp(y)) return x.toString() === y.toString();
255
+ if (typeof x !== "object" || x === null || typeof y !== "object" || y === null) return false;
256
+ const keysX = Reflect.ownKeys(x);
257
+ const keysY = Reflect.ownKeys(y);
258
+ if (keysX.length !== keysY.length) return false;
259
+ for (const key of keysX) {
260
+ if (!Reflect.has(y, key)) return false;
261
+ if (!isEqual(x[key], y[key])) return false;
262
+ }
263
+ return true;
264
+ }
265
+
266
+ //#endregion
267
+ //#region src/utils/typeof/isError.ts
268
+ /**
269
+ * 检查 value 是否为 Error 对象
270
+ * @param value 待检查值
271
+ * @returns 是否为 Error
272
+ */
273
+ function isError(value) {
274
+ return value instanceof Error || resolvePrototypeString(value) === PROTOTYPE_TAGS.error;
275
+ }
276
+
277
+ //#endregion
278
+ //#region src/utils/typeof/isFalsy.ts
279
+ /**
280
+ * 检查 value 是否为 Falsy 值 (false, 0, "", null, undefined, NaN)
281
+ * @param value 待检查值
282
+ * @returns 是否为 Falsy
283
+ */
284
+ function isFalsy(value) {
285
+ if (isNaN(value) || isNull(value) || isUndefined(value)) return true;
286
+ return value === false || value === 0 || value === 0n || value === "";
287
+ }
288
+ function isFalsyLike(value) {
289
+ if (isFalsy(value)) return true;
290
+ return typeof value === "string" && (value === "null" || value === "undefined" || value === "NaN" || value === "false" || value === "0" || value === "0n");
291
+ }
292
+
293
+ //#endregion
294
+ //#region src/utils/typeof/isIterable.ts
295
+ /**
296
+ * 检查 value 是否为可迭代对象 (Iterable)
297
+ * @param value 待检查值
298
+ * @returns 是否为 Iterable
299
+ */
300
+ function isIterable(value) {
301
+ return !!value && typeof value[Symbol.iterator] === "function";
302
+ }
303
+
304
+ //#endregion
305
+ //#region src/utils/typeof/isMap.ts
306
+ /**
307
+ * 检查 value 是否为 Map
308
+ * @param value 待检查值
309
+ * @returns 是否为 Map
310
+ */
311
+ function isMap(value) {
312
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.map;
313
+ }
314
+ /**
315
+ * 检查 value 是否为 WeakMap
316
+ * @param value 待检查值
317
+ * @returns 是否为 WeakMap
318
+ */
319
+ function isWeakMap(value) {
320
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.weakMap;
321
+ }
322
+
323
+ //#endregion
324
+ //#region src/utils/typeof/isNull.ts
325
+ /**
326
+ * 检查 value 是否为 null
327
+ * @param value 待检查值
328
+ * @returns 是否为 null
329
+ */
330
+ function isNull(value) {
331
+ return value === null;
332
+ }
333
+
334
+ //#endregion
335
+ //#region src/utils/typeof/isNumber.ts
336
+ /**
337
+ * 检查 value 是否为 number 类型
338
+ *
339
+ * @param value 待检查值
340
+ * @param NaNCheck 是否排除 `NaN`,默认为 `true`
341
+ * @returns 是否为 number
342
+ * @example
343
+ * ```ts
344
+ * isNumber(1); // true
345
+ * isNumber(NaN); // false (default)
346
+ * isNumber(NaN, false); // true
347
+ * ```
348
+ */
349
+ function isNumber(value, NaNCheck = true) {
350
+ return typeof value === "number" && (!NaNCheck || !isNaN(value));
351
+ }
352
+ /**
353
+ * 检查 value 是否为 NaN
354
+ *
355
+ * @param value 待检查值
356
+ * @returns 是否为 NaN
357
+ */
358
+ function isNaN(value) {
359
+ return Number.isNaN(value);
360
+ }
361
+ /**
362
+ * 检查 value 是否为整数
363
+ *
364
+ * @param value 待检查值
365
+ * @param safeCheck 是否附加安全数检查
366
+ * @returns 是否为整数
367
+ */
368
+ function isInteger(value, safeCheck = true) {
369
+ const check = Number.isInteger(value);
370
+ return safeCheck ? check && Number.isSafeInteger(value) : check;
371
+ }
372
+ /**
373
+ * 检查 value 是否为正整数
374
+ * - 此函数中 `0` 不被视为正整数
375
+ *
376
+ * @param value 待检查值
377
+ * @param safeCheck 是否附加安全数检查
378
+ */
379
+ function isPositiveInteger(value, safeCheck = true) {
380
+ return isInteger(value, safeCheck) && value > 0;
381
+ }
382
+ /**
383
+ * 检查 value 是否为负整数
384
+ * - 此函数中 `0` 不被视为负整数
385
+ *
386
+ * @param value 待检查值
387
+ * @param safeCheck 是否附加安全数检查
388
+ */
389
+ function isNegativeInteger(value, safeCheck = true) {
390
+ return isInteger(value, safeCheck) && value < 0;
391
+ }
392
+ /**
393
+ * 检查 value 是否为 Infinity
394
+ * - 排除 `NaN`
395
+ *
396
+ * @param value 待检查值
397
+ */
398
+ function isInfinity(value) {
399
+ return isNumber(value) && (Number.POSITIVE_INFINITY === value || Number.NEGATIVE_INFINITY === value);
400
+ }
401
+ /**
402
+ * 检查 value 是否类似 Infinity
403
+ * - 排除 `NaN`
404
+ *
405
+ * @param value 待检查值
406
+ */
407
+ function isInfinityLike(value) {
408
+ const check = isInfinity(value);
409
+ if (check) return check;
410
+ if (typeof value === "string") {
411
+ const v = value.trim().toLowerCase();
412
+ return v === "infinity" || v === "-infinity" || v === "+infinity";
413
+ }
414
+ return false;
415
+ }
416
+
417
+ //#endregion
418
+ //#region src/utils/typeof/isObject.ts
419
+ /**
420
+ * 判断是否为对象类型
421
+ * - 可选是否检查原型为 `Object.prototype`,防止原型链污染
422
+ *
423
+ * @param value 待检查值
424
+ * @param prototypeCheck 是否进行原型检查,默认 `true`
425
+ * @returns 是否为 Plain Object (当 checkPrototype=true) 或 object
426
+ * @example
427
+ * ```ts
428
+ * isObject({}); // true
429
+ * isObject(new Date()); // false (because prototype is not Object.prototype)
430
+ * isObject(new Date(), false); // true (is object type)
431
+ * ```
432
+ */
433
+ function isObject(value, prototypeCheck = true) {
434
+ const check = resolvePrototypeString(value) === PROTOTYPE_TAGS.object;
435
+ return prototypeCheck ? check && Object.getPrototypeOf(value) === Object.prototype : check;
436
+ }
437
+
438
+ //#endregion
439
+ //#region src/utils/typeof/isPromise.ts
440
+ /**
441
+ * 检查 value 是否为 Promise
442
+ * @param value 待检查值
443
+ * @returns 是否为 Promise
444
+ */
445
+ function isPromise(value) {
446
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.promise;
447
+ }
448
+ /**
449
+ * 检查 value 是否为 PromiseLike (thenable)
450
+ * @param value 待检查值
451
+ * @returns 是否为 PromiseLike
452
+ */
453
+ function isPromiseLike(value) {
454
+ return isPromise(value) || isObject(value) && isFunction(value["then"]);
455
+ }
456
+
457
+ //#endregion
458
+ //#region src/utils/typeof/isReadableStream.ts
459
+ /**
460
+ * Checks if a value is a WHATWG ReadableStream instance.
461
+ *
462
+ * - Uses `Object.prototype.toString` where supported (modern browsers, Node.js ≥18).
463
+ * - Falls back to duck-typing in older environments.
464
+ * - Resistant to basic forgery, but not 100% secure in all polyfill scenarios.
465
+ *
466
+ * ⚠️ Note: In older Node.js (<18) or with non-compliant polyfills, this may return false positives or negatives.
467
+ */
468
+ /**
469
+ * 检查 value 是否为 ReadableStream
470
+ * @param value 待检查值
471
+ * @returns 是否为 ReadableStream
472
+ */
473
+ function isReadableStream(value) {
474
+ if (resolvePrototypeString(value) === PROTOTYPE_TAGS.readableStream) return true;
475
+ return isObject(value) && isFunction(value["getReader"]) && isFunction(value["pipeThrough"]);
476
+ }
477
+
478
+ //#endregion
479
+ //#region src/utils/typeof/isString.ts
480
+ /**
481
+ * 检查 value 是否为 string 类型
482
+ *
483
+ * @param value 待检查值
484
+ * @param checkEmpty 是否排除空字符串
485
+ * @returns 是否为字符串
486
+ * @example
487
+ * ```ts
488
+ * isString("abc"); // true
489
+ * isString(""); // true
490
+ * isString("", true); // false
491
+ * ```
492
+ */
493
+ function isString(value, checkEmpty = false) {
494
+ return typeof value === "string" && (!checkEmpty || !!value.length);
495
+ }
496
+
497
+ //#endregion
498
+ //#region src/utils/typeof/isRegExp.ts
499
+ /**
500
+ * 检查 value 是否为 RegExp
501
+ * @param value 待检查值
502
+ * @returns 是否为 RegExp
503
+ */
504
+ function isRegExp(value) {
505
+ if (typeof value !== "object" || value === null) return false;
506
+ try {
507
+ const regex = value;
508
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.regExp && isString(regex.source) && isString(regex.flags) && isBoolean(regex.global) && isFunction(regex.test);
509
+ } catch (error) {
510
+ return false;
511
+ }
512
+ }
513
+
514
+ //#endregion
515
+ //#region src/utils/typeof/isSet.ts
516
+ /**
517
+ * 检查 value 是否为 Set
518
+ * @param value 待检查值
519
+ * @returns 是否为 Set
520
+ */
521
+ function isSet(value) {
522
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.set;
523
+ }
524
+ /**
525
+ * 检查 value 是否为 WeakSet
526
+ * @param value 待检查值
527
+ * @returns 是否为 WeakSet
528
+ */
529
+ function isWeakSet(value) {
530
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.weakSet;
531
+ }
532
+
533
+ //#endregion
534
+ //#region src/utils/typeof/isSymbol.ts
535
+ /**
536
+ * 检查 value 是否为 Symbol
537
+ * @param value 待检查值
538
+ * @returns 是否为 Symbol
539
+ */
540
+ function isSymbol(value) {
541
+ return typeof value === "symbol";
542
+ }
543
+
544
+ //#endregion
545
+ //#region src/utils/typeof/isUndefined.ts
546
+ /**
547
+ * 检查 value 是否为 undefined
548
+ * @param value 待检查值
549
+ * @returns 是否为 undefined
550
+ */
551
+ function isUndefined(value) {
552
+ return typeof value === "undefined";
553
+ }
554
+
555
+ //#endregion
556
+ //#region src/utils/typeof/isURLSearchParams.ts
557
+ /**
558
+ * 检查 value 是否为 URLSearchParams
559
+ * @param value 待检查值
560
+ * @returns 是否为 URLSearchParams
561
+ */
562
+ function isURLSearchParams(value) {
563
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.URLSearchParams;
564
+ }
565
+
566
+ //#endregion
567
+ //#region src/utils/typeof/isWebSocket.ts
568
+ /**
569
+ * 检查 value 是否为 WebSocket
570
+ * @param value 待检查值
571
+ * @returns 是否为 WebSocket
572
+ */
573
+ function isWebSocket(value) {
574
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.webSocket;
575
+ }
576
+
577
+ //#endregion
578
+ //#region src/utils/typeof/isWindow.ts
579
+ /**
580
+ * 检查 value 是否为 Window
581
+ * @param value 待检查值
582
+ * @returns 是否为 Window
583
+ */
584
+ function isWindow(value) {
585
+ return resolvePrototypeString(value) === PROTOTYPE_TAGS.window;
586
+ }
587
+
588
+ //#endregion
589
+ //#region src/utils/array/arrayCast.ts
590
+ function arrayCast(candidate, checkEmpty = true) {
591
+ if (checkEmpty && (isUndefined(candidate) || isNull(candidate))) return [];
592
+ return isArray(candidate) ? [...candidate] : [candidate];
593
+ }
594
+
595
+ //#endregion
596
+ //#region src/utils/array/arrayCompete.ts
597
+ /**
598
+ * 数组竞争
599
+ * - 返回在匹配函数的比较条件中获胜的最终项目,适用于更复杂的最小值/最大值计算
600
+ *
601
+ * @param initialList 数组
602
+ * @param match 匹配函数
603
+ * @returns 获胜的元素,如果数组为空或参数无效则返回 `null`
604
+ * @example
605
+ * ```ts
606
+ * const list = [1, 10, 5];
607
+ * arrayCompete(list, (a, b) => (a > b ? a : b)); // 10
608
+ * arrayCompete(list, (a, b) => (a < b ? a : b)); // 1
609
+ * ```
610
+ */
611
+ function arrayCompete(initialList, match) {
612
+ if (!isArray(initialList) || initialList.length === 0 || !isFunction(match)) return null;
613
+ return initialList.reduce(match);
614
+ }
615
+
616
+ //#endregion
617
+ //#region src/utils/array/arrayCounting.ts
618
+ /**
619
+ * 统计数组的项目出现次数
620
+ * - 通过给定的标识符匹配函数,返回一个对象,其中键是回调函数返回的 key 值,每个值是一个整数,表示该 key 出现的次数
621
+ *
622
+ * @param initialList 初始数组
623
+ * @param match 匹配函数
624
+ * @returns 统计对象
625
+ * @example
626
+ * ```ts
627
+ * const list = ["a", "b", "a", "c"];
628
+ * arrayCounting(list, (x) => x); // { a: 2, b: 1, c: 1 }
629
+ *
630
+ * const users = [{ id: 1, group: "A" }, { id: 2, group: "B" }, { id: 3, group: "A" }];
631
+ * arrayCounting(users, (u) => u.group); // { A: 2, B: 1 }
632
+ * ```
633
+ */
634
+ function arrayCounting(initialList, match) {
635
+ if (!isArray(initialList) || !isFunction(match)) return {};
636
+ return initialList.reduce((prev, curr, index) => {
637
+ const id = match(curr, index).toString();
638
+ prev[id] = (prev[id] ?? 0) + 1;
639
+ return prev;
640
+ }, {});
641
+ }
642
+
643
+ //#endregion
644
+ //#region src/utils/array/arrayDifference.ts
645
+ /**
646
+ * 求数组差集
647
+ * - 返回在 `initialList` 中存在,但在 `diffList` 中不存在的元素
648
+ *
649
+ * @param initialList 初始数组
650
+ * @param diffList 对比数组
651
+ * @param match 匹配函数
652
+ * @returns 差集数组
653
+ * @example
654
+ * ```ts
655
+ * arrayDifference([1, 2, 3], [2, 3, 4]); // [1]
656
+ * arrayDifference([{ id: 1 }, { id: 2 }], [{ id: 2 }], (x) => x.id); // [{ id: 1 }]
657
+ * ```
658
+ */
659
+ function arrayDifference(initialList, diffList, match) {
660
+ if (!isArray(initialList) && !isArray(diffList)) return [];
661
+ if (!isArray(initialList) || !initialList.length) return [];
662
+ if (!isArray(diffList) || !diffList.length) return [...initialList];
663
+ if (!isFunction(match)) {
664
+ const arraySet = new Set(diffList);
665
+ return Array.from(new Set(initialList.filter((item) => !arraySet.has(item))));
666
+ }
667
+ const map = /* @__PURE__ */ new Map();
668
+ diffList.forEach((item, index) => {
669
+ map.set(match(item, index), true);
670
+ });
671
+ return initialList.filter((item, index) => !map.get(match(item, index)));
672
+ }
673
+
674
+ //#endregion
675
+ //#region src/utils/array/arrayFirst.ts
676
+ function arrayFirst(initialList, saveValue) {
677
+ if (!isArray(initialList) || initialList.length === 0) return saveValue;
678
+ return initialList[0];
679
+ }
680
+
681
+ //#endregion
682
+ //#region src/utils/array/arrayFork.ts
683
+ /**
684
+ * 数组分组过滤
685
+ * - 给定一个数组和一个条件,返回一个由两个数组组成的元组,其中第一个数组包含所有满足条件的项,第二个数组包含所有不满足条件的项
686
+ *
687
+ * @param initialList 初始数组
688
+ * @param match 条件匹配函数
689
+ * @returns [满足条件的项[], 不满足条件的项[]]
690
+ * @example
691
+ * ```ts
692
+ * arrayFork([1, 2, 3, 4], (n) => n % 2 === 0); // [[2, 4], [1, 3]]
693
+ * ```
694
+ */
695
+ function arrayFork(initialList, match) {
696
+ const forked = [[], []];
697
+ if (isArray(initialList)) initialList.forEach((item, index) => {
698
+ forked[match(item, index) ? 0 : 1].push(item);
699
+ });
700
+ return forked;
701
+ }
702
+
703
+ //#endregion
704
+ //#region src/utils/array/arrayIntersection.ts
705
+ /**
706
+ * 求数组交集
707
+ * - 返回在 `initialList` 和 `diffList` 中都存在的元素
708
+ *
709
+ * @param initialList 初始数组
710
+ * @param diffList 对比数组
711
+ * @param match 匹配函数
712
+ * @returns 交集数组
713
+ * @example
714
+ * ```ts
715
+ * arrayIntersection([1, 2], [2, 3]); // [2]
716
+ * arrayIntersection([{ id: 1 }, { id: 2 }], [{ id: 2 }], (x) => x.id); // [{ id: 2 }]
717
+ * ```
718
+ */
719
+ function arrayIntersection(initialList, diffList, match) {
720
+ if (!isArray(initialList) || !isArray(diffList)) return [];
721
+ if (!initialList.length || !diffList.length) return [];
722
+ if (!isFunction(match)) {
723
+ const diffSet = new Set(diffList);
724
+ return initialList.filter((item) => diffSet.has(item));
725
+ }
726
+ const diffKeys = new Set(diffList.map((item, index) => match(item, index)));
727
+ return initialList.filter((item, index) => diffKeys.has(match(item, index)));
728
+ }
729
+
730
+ //#endregion
731
+ //#region src/utils/array/arrayLast.ts
732
+ function arrayLast(initialList, saveValue) {
733
+ if (!isArray(initialList) || initialList.length === 0) return saveValue;
734
+ return initialList[initialList.length - 1];
735
+ }
736
+
737
+ //#endregion
738
+ //#region src/utils/array/arrayMerge.ts
739
+ /**
740
+ * 数组合并
741
+ * - 如果未提供 `match` 函数,则合并两个数组并去重(Union)
742
+ * - 如果提供了 `match` 函数,则仅更新 `initialList` 中匹配到的项(Left Join Update),不会追加 `mergeList` 中新增的项
743
+ *
744
+ * @param initialList 初始数组
745
+ * @param mergeList 待合并数组
746
+ * @param match 匹配函数
747
+ * @returns 合并后的数组
748
+ * @example
749
+ * ```ts
750
+ * // 基础合并去重
751
+ * arrayMerge([1, 2], [2, 3]); // [1, 2, 3]
752
+ *
753
+ * // 按条件更新
754
+ * const source = [{ id: 1, val: "a" }, { id: 2, val: "b" }];
755
+ * const update = [{ id: 2, val: "new" }, { id: 3, val: "c" }];
756
+ * arrayMerge(source, update, (x) => x.id);
757
+ * // [{ id: 1, val: "a" }, { id: 2, val: "new" }] -> id:3 被忽略
758
+ * ```
759
+ */
760
+ function arrayMerge(initialList, mergeList, match) {
761
+ if (!isArray(initialList)) return [];
762
+ if (!isArray(mergeList)) return [...initialList];
763
+ if (!isFunction(match)) return Array.from(new Set([...initialList, ...mergeList]));
764
+ const keys = /* @__PURE__ */ new Map();
765
+ mergeList.forEach((item, index) => {
766
+ keys.set(match(item, index), item);
767
+ });
768
+ return initialList.map((prevItem, index) => {
769
+ const key = match(prevItem, index);
770
+ return keys.has(key) ? keys.get(key) : prevItem;
771
+ });
772
+ }
773
+
774
+ //#endregion
775
+ //#region src/utils/array/arrayPick.ts
776
+ function arrayPick(initialList, filter, mapper) {
777
+ if (!isArray(initialList)) return [];
778
+ if (!isFunction(filter)) return [...initialList];
779
+ const hasMapper = isFunction(mapper);
780
+ return initialList.reduce((prev, curr, index) => {
781
+ if (!filter(curr, index)) return prev;
782
+ if (hasMapper) prev.push(mapper(curr, index));
783
+ else prev.push(curr);
784
+ return prev;
785
+ }, []);
786
+ }
787
+
788
+ //#endregion
789
+ //#region src/utils/array/arrayReplace.ts
790
+ /**
791
+ * 数组项替换
792
+ * - 在给定的数组中,替换符合匹配函数结果的项目
793
+ * - 只替换第一个匹配项
794
+ *
795
+ * @param initialList 初始数组
796
+ * @param newItem 替换项
797
+ * @param match 匹配函数
798
+ * @returns 替换后的新数组
799
+ * @example
800
+ * ```ts
801
+ * arrayReplace([1, 2, 3], 4, (n) => n === 2); // [1, 4, 3]
802
+ * ```
803
+ */
804
+ function arrayReplace(initialList, newItem, match) {
805
+ if (!isArray(initialList) || !initialList.length) return [];
806
+ if (newItem === void 0 || !isFunction(match)) return [...initialList];
807
+ for (let i = 0; i < initialList.length; i++) {
808
+ const item = initialList[i];
809
+ if (item !== void 0 && match(item, i)) return [
810
+ ...initialList.slice(0, i),
811
+ newItem,
812
+ ...initialList.slice(i + 1, initialList.length)
813
+ ];
814
+ }
815
+ return [...initialList];
816
+ }
817
+
818
+ //#endregion
819
+ //#region src/utils/array/arrayReplaceMove.ts
820
+ /**
821
+ * 数组项替换并移动
822
+ * - 在给定的数组中,替换并移动符合匹配函数结果的项目
823
+ * - 只替换和移动第一个匹配项
824
+ * - 未匹配时,根据 `position` 在指定位置插入 `newItem`
825
+ *
826
+ * @param initialList 初始数组
827
+ * @param newItem 替换项
828
+ * @param match 匹配函数
829
+ * @param position 移动位置,可选 `start` | `end` | 索引位置, 默认为 `end`
830
+ * @returns
831
+ * @example
832
+ * ```ts
833
+ * arrayReplaceMove([1, 2, 3, 4], 5, (n) => n === 2, 0); // [5, 1, 3, 4]
834
+ * arrayReplaceMove([1, 2, 3, 4], 5, (n) => n === 2, 2); // [1, 3, 5, 4]
835
+ * arrayReplaceMove([1, 2, 3, 4], 5, (n) => n === 2, "start"); // [5, 1, 3, 4]
836
+ * arrayReplaceMove([1, 2, 3, 4], 5, (n) => n === 2); // [1, 3, 4, 5]
837
+ * ```
838
+ */
839
+ function arrayReplaceMove(initialList, newItem, match, position) {
840
+ if (!isArray(initialList)) return [];
841
+ if (!initialList.length) return [newItem];
842
+ if (newItem === void 0 || !isFunction(match)) return [...initialList];
843
+ const result = [...initialList];
844
+ const matchIndex = initialList.findIndex(match);
845
+ if (matchIndex !== -1) result.splice(matchIndex, 1);
846
+ if (position === "start") result.unshift(newItem);
847
+ else if (position === 0 || isPositiveInteger(position, false)) result.splice(Math.min(position, result.length), 0, newItem);
848
+ else result.push(newItem);
849
+ return result;
850
+ }
851
+
852
+ //#endregion
853
+ //#region src/utils/array/arraySplit.ts
854
+ /**
855
+ * 数组切分
856
+ * - 将数组以指定的长度切分后,组合在高维数组中
857
+ *
858
+ * @param initialList 初始数组
859
+ * @param size 分割尺寸,默认 `10`
860
+ * @returns 切分后的二维数组
861
+ * @example
862
+ * ```ts
863
+ * arraySplit([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
864
+ * ```
865
+ */
866
+ function arraySplit(initialList, size = 10) {
867
+ if (!isArray(initialList)) return [];
868
+ const count = Math.ceil(initialList.length / size);
869
+ return Array.from({ length: count }).fill(null).map((_c, i) => {
870
+ return initialList.slice(i * size, i * size + size);
871
+ });
872
+ }
873
+
874
+ //#endregion
875
+ //#region src/utils/array/arrayZip.ts
876
+ /**
877
+ * 数组解压
878
+ * - `arrayZip` 的反向操作
879
+ *
880
+ * @param arrays 压缩后的数组
881
+ * @returns 解压后的二维数组
882
+ * @example
883
+ * ```ts
884
+ * arrayUnzip([[1, "a"], [2, "b"]]); // [[1, 2], ["a", "b"]]
885
+ * ```
886
+ */
887
+ function arrayUnzip(arrays) {
888
+ if (!isArray(arrays) || !arrays.length) return [];
889
+ const out = new Array(arrays.reduce((max, arr) => Math.max(max, arr.length), 0));
890
+ let index = 0;
891
+ const get = (array) => array[index];
892
+ for (; index < out.length; index++) out[index] = Array.from(arrays, get);
893
+ return out;
894
+ }
895
+ function arrayZip(...arrays) {
896
+ return arrayUnzip(arrays);
897
+ }
898
+
899
+ //#endregion
900
+ //#region src/utils/array/arrayZipToObject.ts
901
+ function arrayZipToObject(keys, values) {
902
+ const result = {};
903
+ if (!isArray(keys) || !keys.length) return result;
904
+ const getValue = isFunction(values) ? values : isArray(values) ? (_k, i) => values[i] : (_k, _i) => values;
905
+ return keys.reduce((acc, key, idx) => {
906
+ acc[key] = getValue(key, idx);
907
+ return acc;
908
+ }, result);
909
+ }
910
+
911
+ //#endregion
912
+ //#region src/utils/device/isBrowser.ts
913
+ function isBrowser() {
914
+ return typeof window !== "undefined" && isFunction(window?.document?.createElement);
915
+ }
916
+ function isWebWorker() {
917
+ return typeof window === "undefined" && typeof self !== "undefined" && "importScripts" in self;
918
+ }
919
+
920
+ //#endregion
921
+ //#region src/utils/device/isMobile.ts
922
+ /**
923
+ * 检测当前设备是否为移动设备
924
+ *
925
+ * @param maxWidth - 移动设备最大宽度(默认 768px)
926
+ * @param dpi - 标准 DPI 基准(默认 160)
927
+ * @returns 是否为移动设备
928
+ * @example
929
+ * ```ts
930
+ * // 假设 window.innerWidth = 500
931
+ * isMobile(); // true
932
+ * ```
933
+ */
934
+ function isMobile(maxWidth = 768, dpi = 160) {
935
+ if (typeof window === "undefined" || !isPositiveInteger(maxWidth)) return false;
936
+ return !isTablet(maxWidth, 1200, dpi);
937
+ }
938
+ /**
939
+ * 检测当前设备是否为IOS移动设备
940
+ *
941
+ * @param maxWidth - 移动设备最大宽度(默认 768px)
942
+ * @param dpi - 标准 DPI 基准(默认 160)
943
+ * @returns 是否为 iOS 移动设备 (iPhone/iPad/iPod 且非平板)
944
+ * @example
945
+ * ```ts
946
+ * // UA contains iPhone
947
+ * isIOSMobile(); // true
948
+ * ```
949
+ */
950
+ function isIOSMobile(maxWidth = 768, dpi = 160) {
951
+ if (typeof navigator === "undefined" || !navigator.userAgent || !isPositiveInteger(maxWidth)) return false;
952
+ return /iPhone|iPad|iPod/i.test(navigator.userAgent) && !isTablet(maxWidth, 1200, dpi);
953
+ }
954
+
955
+ //#endregion
956
+ //#region src/utils/device/isTablet.ts
957
+ /**
958
+ * 检测当前设备是否为平板
959
+ *
960
+ * @param minWidth - 平板最小宽度(默认 768px)
961
+ * @param maxWidth - 平板最大宽度(默认 1200px)
962
+ * @param dpi - 标准 DPI 基准(默认 160)
963
+ * @returns 是否为平板设备
964
+ * @example
965
+ * ```ts
966
+ * // 假设 window.innerWidth = 1000
967
+ * isTablet(); // true
968
+ * ```
969
+ */
970
+ function isTablet(minWidth = 768, maxWidth = 1200, dpi = 160) {
971
+ if (typeof window === "undefined" || !isPositiveInteger(minWidth) || !isPositiveInteger(maxWidth)) return false;
972
+ const width = window.innerWidth;
973
+ const isWithinWidthRange = width >= minWidth && width <= maxWidth;
974
+ try {
975
+ const widthPx = window.screen.width;
976
+ const heightPx = window.screen.height;
977
+ const DPI = dpi * (window.devicePixelRatio || 1);
978
+ const widthInch = widthPx / DPI;
979
+ const heightInch = heightPx / DPI;
980
+ const screenInches = Math.sqrt(widthInch ** 2 + heightInch ** 2);
981
+ return isWithinWidthRange || screenInches >= 7;
982
+ } catch {
983
+ return isWithinWidthRange;
984
+ }
985
+ }
986
+
987
+ //#endregion
988
+ //#region src/utils/function/to.ts
989
+ /**
990
+ *将 Promise 转换为 `[err, result]` 格式,方便 async/await 错误处理
991
+ *
992
+ * @param promise 待处理的 Promise
993
+ * @param errorExt 附加到 error 对象的扩展信息(注意:如果原 error 是 Error 实例,扩展属性可能会覆盖或无法正确合并非枚举属性)
994
+ * @returns `[err, null]` 或 `[null, data]`
995
+ * @example
996
+ * ```ts
997
+ * const [err, data] = await to(someAsyncFunc());
998
+ * if (err) return;
999
+ * console.log(data);
1000
+ * ```
1001
+ */
1002
+ function to(promise, errorExt) {
1003
+ return promise.then((data) => [null, data]).catch((err) => {
1004
+ if (errorExt) {
1005
+ const parsedError = {
1006
+ ...err,
1007
+ ...errorExt
1008
+ };
1009
+ if (err instanceof Error) {
1010
+ parsedError["message"] = err.message;
1011
+ parsedError["stack"] = err.stack;
1012
+ }
1013
+ return [parsedError, void 0];
1014
+ }
1015
+ return [err ? err : /* @__PURE__ */ new Error("defaultError"), void 0];
1016
+ });
1017
+ }
1018
+
1019
+ //#endregion
1020
+ //#region src/utils/string/stringToNumber.ts
1021
+ const R1$2 = /[^0-9.-]/g;
1022
+ /**
1023
+ * 从字符串中提取数字字符串
1024
+ *
1025
+ /**
1026
+ * 从字符串中提取数字字符串
1027
+ * - 移除非数字字符,保留符号和小数点
1028
+ *
1029
+ * @param input 待处理字符串
1030
+ * @returns 提取出的数字字符串
1031
+ * @example
1032
+ * ```ts
1033
+ * stringToNumber("$1,234.56"); // "1234.56"
1034
+ * stringToNumber("abc-123"); // "-123"
1035
+ * ```
1036
+ */
1037
+ function stringToNumber(input) {
1038
+ if (!isString(input, true)) return "";
1039
+ const cleaned = input.replace(R1$2, "");
1040
+ let isDecimal = false;
1041
+ let signCount = 0;
1042
+ let firstIndex = -1;
1043
+ const stringList = cleaned.split("").map((s, i) => {
1044
+ if (s === ".") {
1045
+ if (isDecimal) return "";
1046
+ isDecimal = true;
1047
+ return ".";
1048
+ }
1049
+ if (s === "-") {
1050
+ firstIndex === -1 && signCount++;
1051
+ return "";
1052
+ }
1053
+ firstIndex === -1 && (firstIndex = i);
1054
+ return s;
1055
+ });
1056
+ const sign = signCount % 2 === 1 ? "-" : "";
1057
+ if (firstIndex === -1) return sign + "0";
1058
+ let result = stringList.join("");
1059
+ if (result.startsWith(".")) result = "0" + result;
1060
+ if (result.endsWith(".")) result = result.slice(0, -1);
1061
+ return sign + result;
1062
+ }
1063
+
1064
+ //#endregion
1065
+ //#region src/utils/math/toMathBignumber.ts
1066
+ /**
1067
+ * 将任意类型的值转换为 `math.bignumber`
1068
+ *
1069
+ * @param mathJsInstance mathJs 实例
1070
+ * @param value 任意类型的值
1071
+ * @param saveValue 安全值
1072
+ * @returns 转换后的 BigNumber
1073
+ * @example
1074
+ * ```ts
1075
+ * import { create, all } from "mathjs";
1076
+ * const math = create(all);
1077
+ * toMathBignumber(math, "0.1");
1078
+ * ```
1079
+ */
1080
+ function toMathBignumber(mathJsInstance, value, saveValue) {
1081
+ const errorValue = saveValue ?? mathJsInstance.bignumber(0);
1082
+ if (isFalsyLike(value) || isInfinityLike(value)) return errorValue;
1083
+ try {
1084
+ return mathJsInstance.bignumber(stringToNumber(`${value}`));
1085
+ } catch (error) {
1086
+ return errorValue;
1087
+ }
1088
+ }
1089
+
1090
+ //#endregion
1091
+ //#region src/utils/math/toMathDecimal.ts
1092
+ function toMathDecimal(mathJsInstance, value, precision, isFormat = true) {
1093
+ const bigNumber = toMathBignumber(mathJsInstance, value);
1094
+ return isFormat ? mathJsInstance.format(bigNumber, {
1095
+ notation: "fixed",
1096
+ precision
1097
+ }) : bigNumber;
1098
+ }
1099
+
1100
+ //#endregion
1101
+ //#region src/utils/math/toMathEvaluate.ts
1102
+ /**
1103
+ * 数学表达式求值
1104
+ *
1105
+ * @param mathJsInstance mathJs 实例
1106
+ * @param expr 表达式
1107
+ * @param scope 键值映射
1108
+ * @returns 计算结果的字符串表示
1109
+ * @example
1110
+ * ```ts
1111
+ * toMathEvaluate(math, "a + b", { a: 1, b: 2 }); // "3"
1112
+ * ```
1113
+ */
1114
+ function toMathEvaluate(mathJsInstance, expr, scope) {
1115
+ const evaluateValue = `${mathJsInstance.evaluate(expr, scope || {})}`;
1116
+ return mathJsInstance.format(toMathBignumber(mathJsInstance, evaluateValue), { notation: "fixed" });
1117
+ }
1118
+
1119
+ //#endregion
1120
+ //#region src/utils/number/isWithinInterval.ts
1121
+ /**
1122
+ * 数字区间检查函数
1123
+ *
1124
+ * @param input 待检查数字
1125
+ * @param interval 由两个数字组成的元组 [left, right]
1126
+ * @param includeLeft 是否包含左边界(默认 true)
1127
+ * @param includeRight 是否包含右边界(默认 false)
1128
+ * @returns 是否在区间内
1129
+ * @example
1130
+ * ```ts
1131
+ * isWithinInterval(5, [1, 10]); // true
1132
+ * isWithinInterval(1, [1, 10], false); // false
1133
+ * ```
1134
+ */
1135
+ function isWithinInterval(input, interval, includeLeft = true, includeRight = false) {
1136
+ if (!isNumber(input)) throw new Error("params [input] mast be a number.");
1137
+ if (isInfinity(input)) throw new Error("params [input] mast be a finite number.");
1138
+ const [left, right] = interval;
1139
+ if (left > right) throw new Error(`Invalid interval: left (${left}) must be <= right (${right}).`);
1140
+ if (includeLeft && includeRight) return input >= left && input <= right;
1141
+ else if (includeLeft) return input >= left && input < right;
1142
+ else if (includeRight) return input > left && input <= right;
1143
+ else return input > left && input < right;
1144
+ }
1145
+
1146
+ //#endregion
1147
+ //#region src/utils/object/cloneDeep.ts
1148
+ const defaultCloneStrategy = {
1149
+ cloneMap,
1150
+ cloneSet,
1151
+ cloneDate,
1152
+ cloneArray,
1153
+ cloneObject,
1154
+ cloneOther
1155
+ };
1156
+ function cloneMap(input, track, clone) {
1157
+ const output = track(/* @__PURE__ */ new Map());
1158
+ for (const [key, value] of input) output.set(key, clone(value));
1159
+ return output;
1160
+ }
1161
+ function cloneSet(input, track, clone) {
1162
+ const output = track(/* @__PURE__ */ new Set());
1163
+ for (const value of input) output.add(clone(value));
1164
+ return output;
1165
+ }
1166
+ function cloneDate(input, track) {
1167
+ return track(new Date(input));
1168
+ }
1169
+ function cloneArray(input, track, clone) {
1170
+ const output = track(new Array(input.length));
1171
+ input.forEach((value, index) => {
1172
+ output[index] = clone(value);
1173
+ });
1174
+ return output;
1175
+ }
1176
+ function cloneObject(input, track, clone) {
1177
+ const output = track(Object.create(Object.getPrototypeOf(input)));
1178
+ for (const key of Reflect.ownKeys(input)) {
1179
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
1180
+ if ("value" in descriptor) descriptor.value = clone(descriptor.value);
1181
+ Object.defineProperty(output, key, descriptor);
1182
+ }
1183
+ return output;
1184
+ }
1185
+ function cloneOther(input, track) {
1186
+ return track(input);
1187
+ }
1188
+ /**
1189
+ * 深度拷贝对象
1190
+ * - 支持 Array, Object, Map, Set
1191
+ * - 自动处理循环引用
1192
+ *
1193
+ * @param root 需要拷贝的对象
1194
+ * @param customStrategy 自定义拷贝策略
1195
+ * @returns 拷贝后的对象
1196
+ * @example
1197
+ * ```ts
1198
+ * const original = { a: 1, b: { c: 2 } };
1199
+ * const copy = cloneDeep(original);
1200
+ * copy.b.c = 3;
1201
+ * // original.b.c === 2
1202
+ * ```
1203
+ * @reference https://github.com/radashi-org/radashi/blob/main/src/object/cloneDeep.ts
1204
+ */
1205
+ function cloneDeep(root, customStrategy) {
1206
+ const strategy = {
1207
+ ...defaultCloneStrategy,
1208
+ ...customStrategy
1209
+ };
1210
+ const tracked = /* @__PURE__ */ new Map();
1211
+ const track = (parent, newParent) => {
1212
+ tracked.set(parent, newParent);
1213
+ return newParent;
1214
+ };
1215
+ const clone = (value) => {
1216
+ return value && typeof value === "object" ? tracked.get(value) ?? cloneDeep$1(value, strategy) : value;
1217
+ };
1218
+ const cloneDeep$1 = (parent, strategy$1) => {
1219
+ const newParent = (isObject(parent) ? strategy$1.cloneObject : isArray(parent) ? strategy$1.cloneArray : isMap(parent) ? strategy$1.cloneMap : isSet(parent) ? strategy$1.cloneSet : isDate(parent, false) ? strategy$1.cloneDate : strategy$1.cloneOther)(parent, track.bind(null, parent), clone);
1220
+ if (!newParent) return cloneDeep$1(parent, defaultCloneStrategy);
1221
+ tracked.set(parent, newParent);
1222
+ return newParent;
1223
+ };
1224
+ return cloneDeep$1(root, strategy);
1225
+ }
1226
+
1227
+ //#endregion
1228
+ //#region src/utils/object/enumEntries.ts
1229
+ function enumEntries(enumeration) {
1230
+ const [isEnum, isTwoWayEnum] = isEnumeration(enumeration);
1231
+ if (!isEnum) throw Error("function enumEntries expected parameter is a enum, and requires at least one member");
1232
+ const entries = objectEntries(enumeration);
1233
+ if (isTwoWayEnum) return entries.splice(entries.length / 2, entries.length / 2);
1234
+ return entries;
1235
+ }
1236
+
1237
+ //#endregion
1238
+ //#region src/utils/object/enumKeys.ts
1239
+ function enumKeys(enumeration) {
1240
+ const [isEnum, isTwoWayEnum] = isEnumeration(enumeration);
1241
+ if (!isEnum) throw Error("function enumKeys expected parameter is a enum, and requires at least one member");
1242
+ const keys = objectKeys(enumeration);
1243
+ if (isTwoWayEnum) return keys.splice(keys.length / 2, keys.length / 2);
1244
+ return keys;
1245
+ }
1246
+
1247
+ //#endregion
1248
+ //#region src/utils/object/enumValues.ts
1249
+ function enumValues(enumeration) {
1250
+ const [isEnum, isTwoWayEnum] = isEnumeration(enumeration);
1251
+ if (!isEnum) throw Error("function enumValues expected parameter is a enum, and requires at least one member");
1252
+ const values = objectValues(enumeration);
1253
+ if (isTwoWayEnum) return values.splice(values.length / 2, values.length / 2);
1254
+ return values;
1255
+ }
1256
+
1257
+ //#endregion
1258
+ //#region src/utils/object/objectEntries.ts
1259
+ function objectEntries(value) {
1260
+ return Object.entries(value);
1261
+ }
1262
+
1263
+ //#endregion
1264
+ //#region src/utils/object/mapEntries.ts
1265
+ /**
1266
+ * 映射对象条目
1267
+ * - 将对象的键值对映射为新的键值对
1268
+ *
1269
+ * @param obj 对象
1270
+ * @param toEntry 映射函数
1271
+ * @returns 映射后的新对象
1272
+ * @example
1273
+ * ```ts
1274
+ * const obj = { a: 1, b: 2 };
1275
+ * mapEntries(obj, (k, v) => [k, v * 2]); // { a: 2, b: 4 }
1276
+ * ```
1277
+ */
1278
+ function mapEntries(obj, toEntry) {
1279
+ const defaultResult = {};
1280
+ if (!obj) return defaultResult;
1281
+ return objectEntries(obj).reduce((acc, [key, value]) => {
1282
+ const [newKey, newValue] = toEntry(key, value);
1283
+ acc[newKey] = newValue;
1284
+ return acc;
1285
+ }, defaultResult);
1286
+ }
1287
+
1288
+ //#endregion
1289
+ //#region src/utils/object/objectAssign.ts
1290
+ function objectAssign(initial, override) {
1291
+ if (!isObject(initial) || !isObject(override)) return initial ?? override ?? {};
1292
+ const proto = Object.getPrototypeOf(initial);
1293
+ const assigned = proto ? { ...initial } : Object.assign(Object.create(proto), initial);
1294
+ for (const key of Object.keys(override)) assigned[key] = isObject(initial[key]) && isObject(override[key]) ? objectAssign(initial[key], override[key]) : override[key];
1295
+ return assigned;
1296
+ }
1297
+
1298
+ //#endregion
1299
+ //#region src/utils/object/objectCrush.ts
1300
+ function objectCrush(obj) {
1301
+ if (!obj) return {};
1302
+ function crushReducer(crushed, value, path) {
1303
+ if (isObject(value) || isArray(value)) for (const [prop, propValue] of Object.entries(value)) crushReducer(crushed, propValue, path ? `${path}.${prop}` : prop);
1304
+ else crushed[path] = value;
1305
+ return crushed;
1306
+ }
1307
+ return crushReducer({}, obj, "");
1308
+ }
1309
+
1310
+ //#endregion
1311
+ //#region src/utils/object/objectInvert.ts
1312
+ function objectInvert(obj) {
1313
+ const result = {};
1314
+ if (!isObject(obj)) return result;
1315
+ for (const [k, v] of objectEntries(obj)) if (isString(v) || isNumber(v) || isSymbol(v)) result[v] = k;
1316
+ return result;
1317
+ }
1318
+
1319
+ //#endregion
1320
+ //#region src/utils/object/objectKeys.ts
1321
+ function objectKeys(value) {
1322
+ return Object.keys(value);
1323
+ }
1324
+
1325
+ //#endregion
1326
+ //#region src/utils/object/objectOmit.ts
1327
+ function objectOmit(obj, keys) {
1328
+ const result = {};
1329
+ if (!isObject(obj)) return result;
1330
+ if (!isArray(keys)) return obj;
1331
+ const keysToOmit = new Set(keys);
1332
+ return Object.keys(obj).reduce((acc, key) => {
1333
+ if (!keysToOmit.has(key)) acc[key] = obj[key];
1334
+ return acc;
1335
+ }, result);
1336
+ }
1337
+
1338
+ //#endregion
1339
+ //#region src/utils/object/objectPick.ts
1340
+ function objectPick(obj, keys) {
1341
+ const result = {};
1342
+ if (!isObject(obj)) return result;
1343
+ if (!isArray(keys)) return obj;
1344
+ return keys.reduce((acc, key) => {
1345
+ if (key in obj) acc[key] = obj[key];
1346
+ return acc;
1347
+ }, result);
1348
+ }
1349
+
1350
+ //#endregion
1351
+ //#region src/utils/object/objectValues.ts
1352
+ function objectValues(value) {
1353
+ return Object.values(value);
1354
+ }
1355
+
1356
+ //#endregion
1357
+ //#region src/utils/string/stringInitialCase.ts
1358
+ const R1$1 = /\S+/g;
1359
+ const R2 = /[^a-zA-Z\u00C0-\u017F]/;
1360
+ /**
1361
+ * 字符串首字母大小写
1362
+ * - 包含非西欧字母字符时,不处理
1363
+ * - 纯字母且全大写时,不处理
1364
+ * - 纯字母且非全大写时,首字母小写,其余保留
1365
+ * - 纯字母且非全大写时,首字母大写,其余保留
1366
+ *
1367
+ /**
1368
+ * 字符串首字母大小写
1369
+ * - 包含非西欧字母字符时,不处理
1370
+ * - 纯字母且全大写时,不处理
1371
+ * - 纯字母且非全大写时,首字母小写,其余保留
1372
+ * - 纯字母且非全大写时,首字母大写,其余保留
1373
+ *
1374
+ * @param input 待处理字符串
1375
+ * @param caseType 大小写类型
1376
+ * @returns 处理后的字符串
1377
+ * @example
1378
+ * ```ts
1379
+ * stringInitialCase("Hello", "lower"); // "hello"
1380
+ * stringInitialCase("hello", "upper"); // "Hello"
1381
+ * ```
1382
+ */
1383
+ function stringInitialCase(input, caseType) {
1384
+ if (!isString(input, true)) return "";
1385
+ return input.replace(R1$1, (word) => {
1386
+ if (R2.test(word)) return word;
1387
+ if (word === word.toLocaleUpperCase()) return word;
1388
+ if (caseType === "lower" && word[0]) return word[0].toLocaleLowerCase() + word.slice(1);
1389
+ if (caseType === "upper" && word[0]) return word[0].toLocaleUpperCase() + word.slice(1);
1390
+ return word;
1391
+ });
1392
+ }
1393
+
1394
+ //#endregion
1395
+ //#region src/utils/string/stringReplace.ts
1396
+ /**
1397
+ * 字符串替换
1398
+ * - 替换第一个匹配项
1399
+ *
1400
+ /**
1401
+ * 字符串替换
1402
+ * - 替换第一个匹配项
1403
+ *
1404
+ * @param input 待处理字符串
1405
+ * @param search 匹配项
1406
+ * @param replacement 替换项
1407
+ * @returns 替换后的字符串
1408
+ * @example
1409
+ * ```ts
1410
+ * stringReplace("hello world", "world", "context"); // "hello context"
1411
+ * ```
1412
+ */
1413
+ function stringReplace(input, search, replacement) {
1414
+ if (!isString(input, true)) return "";
1415
+ return input.replace(search, replacement);
1416
+ }
1417
+
1418
+ //#endregion
1419
+ //#region src/utils/string/stringTemplate.ts
1420
+ const R1 = /\{\{(.+?)\}\}/g;
1421
+ /**
1422
+ * 字符串模板替换
1423
+ *
1424
+ /**
1425
+ * 字符串模板替换
1426
+ *
1427
+ * @param input 待处理字符串
1428
+ * @param template 模板对象
1429
+ * @param regex 模板匹配正则 (默认: `\{\{(.+?)\}\}`)
1430
+ * @returns 替换后的字符串
1431
+ * @example
1432
+ * ```ts
1433
+ * stringTemplate("Hello {{name}}", { name: "World" }); // "Hello World"
1434
+ * ```
1435
+ */
1436
+ function stringTemplate(input, template, regex = R1) {
1437
+ if (!isString(input, true)) return "";
1438
+ let result = "";
1439
+ let from = 0;
1440
+ let match;
1441
+ while (match = regex.exec(input)) {
1442
+ result += input.slice(from, match.index) + template[match[1]];
1443
+ from = regex.lastIndex;
1444
+ }
1445
+ return result + input.slice(from);
1446
+ }
1447
+
1448
+ //#endregion
1449
+ //#region src/utils/string/stringToJson.ts
1450
+ /**
1451
+ * 处理 JSON 字符串
1452
+ *
1453
+ /**
1454
+ * 处理 JSON 字符串
1455
+ *
1456
+ * @param input 待处理字符串
1457
+ * @param safeValue 安全值 (当解析失败或输入无效时返回)
1458
+ * @returns 解析后的对象 或 安全值
1459
+ * @example
1460
+ * ```ts
1461
+ * stringToJson('{"a": 1}', {}); // { a: 1 }
1462
+ * stringToJson('invalid', {}); // {}
1463
+ * ```
1464
+ */
1465
+ function stringToJson(input, safeValue) {
1466
+ if (!isString(input, true)) return safeValue;
1467
+ try {
1468
+ return JSON.parse(input);
1469
+ } catch (error) {
1470
+ return safeValue;
1471
+ }
1472
+ }
1473
+
1474
+ //#endregion
1475
+ //#region src/utils/string/stringToPosix.ts
1476
+ /**
1477
+ * 将路径转换为 POSIX 风格
1478
+ *
1479
+ /**
1480
+ * 将路径转换为 POSIX 风格
1481
+ * - 统一使用正斜杠
1482
+ * - 处理 Windows 盘符
1483
+ *
1484
+ * @param input 待处理字符串
1485
+ * @param removeLeadingSlash 是否移除开头斜杠,默认为 `false`
1486
+ * @returns 转换后的路径
1487
+ * @example
1488
+ * ```ts
1489
+ * stringToPosix("C:\\Windows\\System32"); // "/Windows/System32"
1490
+ * ```
1491
+ */
1492
+ function stringToPosix(input, removeLeadingSlash = false) {
1493
+ if (!isString(input, true)) return "";
1494
+ let normalized = input.replace(/^[A-Za-z]:[\\/]?/, "").replace(/^[\\/]+/, "/");
1495
+ normalized = normalized.replace(/\\/g, "/");
1496
+ normalized = normalized.replace(/\/+/g, "/");
1497
+ if (removeLeadingSlash && normalized.startsWith("/")) normalized = normalized.substring(1);
1498
+ return normalized;
1499
+ }
1500
+
1501
+ //#endregion
1502
+ //#region src/utils/string/stringToValues.ts
1503
+ function stringToValues(input, valueType = "number", splitSymbol = ",") {
1504
+ if (!isString(input, true)) return [];
1505
+ try {
1506
+ const values = input.split(splitSymbol);
1507
+ if (valueType === "number") return values.map((d) => Number(d));
1508
+ return values;
1509
+ } catch (error) {
1510
+ return [];
1511
+ }
1512
+ }
1513
+
1514
+ //#endregion
1515
+ //#region src/utils/string/stringTrim.ts
1516
+ /**
1517
+ * 从字符串中裁切掉所有的前缀和后缀字符
1518
+ *
1519
+ * @param input 待处理字符串
1520
+ * @param charsToTrim 裁切字符,默认为 `" "`
1521
+ * @returns 裁切后的字符串
1522
+ * @example
1523
+ * ```ts
1524
+ * stringTrim(" hello "); // "hello"
1525
+ * stringTrim("__hello__", "_"); // "hello"
1526
+ * ```
1527
+ */
1528
+ function stringTrim(input, charsToTrim = " ") {
1529
+ if (!isString(input, true)) return "";
1530
+ const toTrim = charsToTrim.replace(/[\W]{1}/g, "\\$&");
1531
+ const regex = new RegExp(`^[${toTrim}]+|[${toTrim}]+$`, "g");
1532
+ return input.replace(regex, "");
1533
+ }
1534
+
1535
+ //#endregion
1536
+ //#region src/utils/string/stringTruncate.ts
1537
+ /**
1538
+ /**
1539
+ * 截取字符串
1540
+ * - 支持自定义省略符,不会截断在汉字中间(因为JS字符串本身按字符处理)
1541
+ *
1542
+ * @param input 待处理字符串
1543
+ * @param maxLength 最大长度 (包含省略符)
1544
+ * @param ellipsis 省略符,默认为 `...`
1545
+ * @returns 截取后的字符串
1546
+ * @example
1547
+ * ```ts
1548
+ * stringTruncate("hello world", 8); // "hello..."
1549
+ * ```
1550
+ */
1551
+ function stringTruncate(input, maxLength, ellipsis = "...") {
1552
+ if (!isString(input, true)) return "";
1553
+ if (!isPositiveInteger(maxLength)) return input;
1554
+ if (input.length <= maxLength) return input;
1555
+ const truncated = input.slice(0, maxLength - ellipsis.length);
1556
+ return truncated.length > 0 ? truncated + ellipsis : "";
1557
+ }
1558
+
1559
+ //#endregion
1560
+ //#region src/utils/time/timeZone.ts
1561
+ /**
1562
+ * 获取当前时区信息
1563
+ *
1564
+ * @returns 时区信息对象 (UTC偏移和时区名称)
1565
+ * @example
1566
+ * ```ts
1567
+ * getTimeZone(); // { UTC: "UTC+8", timeZone: "Asia/Shanghai" }
1568
+ * ```
1569
+ */
1570
+ function getTimeZone() {
1571
+ const hour = 0 - (/* @__PURE__ */ new Date()).getTimezoneOffset() / 60;
1572
+ return {
1573
+ UTC: "UTC" + (hour >= 0 ? "+" + hour : hour),
1574
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
1575
+ };
1576
+ }
1577
+
1578
+ //#endregion
1579
+ //#region src/utils/tree/types.ts
1580
+ function getFinalChildrenKey(tree, meta, options) {
1581
+ if (isFunction(options.getChildrenKey)) {
1582
+ const dynamicChildrenKey = options.getChildrenKey(tree, meta);
1583
+ if (dynamicChildrenKey && dynamicChildrenKey !== null) return dynamicChildrenKey;
1584
+ }
1585
+ return options.childrenKey;
1586
+ }
1587
+
1588
+ //#endregion
1589
+ //#region src/utils/tree/treeFilter.ts
1590
+ function preImpl$3(row, callback, options) {
1591
+ if (!callback(row, options)) return;
1592
+ const finalChildrenKey = getFinalChildrenKey(row, options, options);
1593
+ const children = row[finalChildrenKey];
1594
+ let newChildren;
1595
+ if (isArray(children)) {
1596
+ const nextLevelOptions = {
1597
+ ...options,
1598
+ parents: [...options.parents, row],
1599
+ depth: options.depth + 1
1600
+ };
1601
+ newChildren = children.map((c) => preImpl$3(c, callback, nextLevelOptions)).filter((c) => !!c);
1602
+ }
1603
+ return {
1604
+ ...row,
1605
+ [finalChildrenKey]: newChildren
1606
+ };
1607
+ }
1608
+ function postImpl$3(row, callback, options) {
1609
+ const finalChildrenKey = getFinalChildrenKey(row, options, options);
1610
+ const children = row[finalChildrenKey];
1611
+ let newChildren;
1612
+ if (isArray(children)) {
1613
+ const nextLevelOptions = {
1614
+ ...options,
1615
+ parents: [...options.parents, row],
1616
+ depth: options.depth + 1
1617
+ };
1618
+ newChildren = children.map((c) => preImpl$3(c, callback, nextLevelOptions)).filter((c) => !!c);
1619
+ }
1620
+ if (!callback(row, options)) return;
1621
+ return {
1622
+ ...row,
1623
+ [finalChildrenKey]: newChildren
1624
+ };
1625
+ }
1626
+ function breadthImpl$3(row, callback, options) {
1627
+ const queue = [{
1628
+ queueRow: row,
1629
+ queueOptions: options
1630
+ }];
1631
+ const resultCache = /* @__PURE__ */ new WeakMap();
1632
+ const newNodeCache = /* @__PURE__ */ new WeakMap();
1633
+ const childrenKeyCache = /* @__PURE__ */ new WeakMap();
1634
+ let result;
1635
+ const runQueue = () => {
1636
+ if (queue.length === 0) return result;
1637
+ const { queueRow, queueOptions } = queue.shift();
1638
+ const finalChildrenKey = getFinalChildrenKey(queueRow, queueOptions, queueOptions);
1639
+ const children = queueRow[finalChildrenKey];
1640
+ if (isArray(children)) {
1641
+ const nextLevelOptions = {
1642
+ ...queueOptions,
1643
+ parents: [...queueOptions.parents, queueRow],
1644
+ depth: queueOptions.depth + 1
1645
+ };
1646
+ const subQueueItems = children.map((queueRow$1) => ({
1647
+ queueRow: queueRow$1,
1648
+ queueOptions: nextLevelOptions
1649
+ }));
1650
+ queue.push(...subQueueItems);
1651
+ }
1652
+ const parent = arrayLast(queueOptions.parents);
1653
+ const isTopNode = queueOptions.depth === 0;
1654
+ const parentResult = parent && resultCache.get(parent);
1655
+ if (!isTopNode && !parentResult) return runQueue();
1656
+ const callbackResult = callback(queueRow, queueOptions);
1657
+ if (isTopNode && !callbackResult) return;
1658
+ const newNode = {
1659
+ ...queueRow,
1660
+ [finalChildrenKey]: void 0
1661
+ };
1662
+ if (isTopNode) result = newNode;
1663
+ resultCache.set(queueRow, callbackResult);
1664
+ newNodeCache.set(queueRow, newNode);
1665
+ childrenKeyCache.set(queueRow, finalChildrenKey);
1666
+ if (callbackResult && parent) {
1667
+ const parentNewNode = newNodeCache.get(parent);
1668
+ const parentChildrenKey = childrenKeyCache.get(parent);
1669
+ if (parentNewNode && parentChildrenKey) {
1670
+ if (!parentNewNode[parentChildrenKey]) parentNewNode[parentChildrenKey] = [];
1671
+ parentNewNode[parentChildrenKey].push(newNode);
1672
+ }
1673
+ }
1674
+ return runQueue();
1675
+ };
1676
+ return runQueue();
1677
+ }
1678
+ const strategies$3 = {
1679
+ pre: preImpl$3,
1680
+ post: postImpl$3,
1681
+ breadth: breadthImpl$3
1682
+ };
1683
+ function treeFilter(tree, callback, options = {}) {
1684
+ const { childrenKey = "children", strategy = "pre", getChildrenKey } = options;
1685
+ const traversalMethod = strategies$3[strategy];
1686
+ const innerOptions = {
1687
+ childrenKey,
1688
+ depth: 0,
1689
+ parents: [],
1690
+ getChildrenKey
1691
+ };
1692
+ return isArray(tree) ? tree.map((row) => traversalMethod(row, callback, innerOptions)).filter((t) => !!t) : traversalMethod(tree, callback, innerOptions) || [];
1693
+ }
1694
+
1695
+ //#endregion
1696
+ //#region src/utils/tree/treeFind.ts
1697
+ const strategies$2 = {
1698
+ pre: preImpl$2,
1699
+ post: postImpl$2,
1700
+ breadth: breadthImpl$2
1701
+ };
1702
+ function preImpl$2(row, callback, options) {
1703
+ if (callback(row, options)) return row;
1704
+ const children = row[getFinalChildrenKey(row, options, options)];
1705
+ if (isArray(children)) for (const child of children) {
1706
+ const result = preImpl$2(child, callback, {
1707
+ ...options,
1708
+ parents: [...options.parents, row],
1709
+ depth: options.depth + 1
1710
+ });
1711
+ if (result) return result;
1712
+ }
1713
+ }
1714
+ function postImpl$2(row, callback, options) {
1715
+ const children = row[getFinalChildrenKey(row, options, options)];
1716
+ if (isArray(children)) for (const child of children) {
1717
+ const result = postImpl$2(child, callback, {
1718
+ ...options,
1719
+ parents: [...options.parents, row],
1720
+ depth: options.depth + 1
1721
+ });
1722
+ if (result) return result;
1723
+ }
1724
+ if (callback(row, options)) return row;
1725
+ }
1726
+ function breadthImpl$2(row, callback, options) {
1727
+ const queue = [{
1728
+ queueRow: row,
1729
+ queueOptions: options
1730
+ }];
1731
+ const runQueue = () => {
1732
+ if (queue.length === 0) return;
1733
+ const { queueRow, queueOptions } = queue.shift();
1734
+ const children = queueRow[getFinalChildrenKey(queueRow, queueOptions, queueOptions)];
1735
+ if (isArray(children)) {
1736
+ const nextLevelOptions = {
1737
+ ...queueOptions,
1738
+ parents: [...queueOptions.parents, queueRow],
1739
+ depth: queueOptions.depth + 1
1740
+ };
1741
+ const subQueueItems = children.map((queueRow$1) => ({
1742
+ queueRow: queueRow$1,
1743
+ queueOptions: nextLevelOptions
1744
+ }));
1745
+ queue.push(...subQueueItems);
1746
+ }
1747
+ if (callback(queueRow, queueOptions)) return queueRow;
1748
+ return runQueue();
1749
+ };
1750
+ return runQueue();
1751
+ }
1752
+ /**
1753
+ * 查找树节点
1754
+ * - 返回第一个回调返回 true 的节点
1755
+ *
1756
+ * @param tree 树结构数据
1757
+ * @param callback 回调函数
1758
+ * @param options 配置项
1759
+ * @returns 找到的节点,未找到则返回 undefined
1760
+ * @example
1761
+ * ```ts
1762
+ * const tree = [{ id: 1, children: [{ id: 2 }] }];
1763
+ * treeFind(tree, (node) => node.id === 2); // { id: 2, ... }
1764
+ * ```
1765
+ */
1766
+ function treeFind(tree, callback, options = {}) {
1767
+ const { childrenKey = "children", strategy = "pre", getChildrenKey } = options;
1768
+ const traversalMethod = strategies$2[strategy];
1769
+ const innerOptions = {
1770
+ childrenKey,
1771
+ depth: 0,
1772
+ parents: [],
1773
+ getChildrenKey
1774
+ };
1775
+ if (isArray(tree)) {
1776
+ for (const row of tree) {
1777
+ const result = traversalMethod(row, callback, innerOptions);
1778
+ if (result) return result;
1779
+ }
1780
+ return;
1781
+ }
1782
+ return traversalMethod(tree, callback, innerOptions);
1783
+ }
1784
+
1785
+ //#endregion
1786
+ //#region src/utils/tree/treeForEach.ts
1787
+ const strategies$1 = {
1788
+ pre: preImpl$1,
1789
+ post: postImpl$1,
1790
+ breadth: breadthImpl$1
1791
+ };
1792
+ function preImpl$1(row, callback, options) {
1793
+ callback(row, options);
1794
+ const children = row[getFinalChildrenKey(row, options, options)];
1795
+ if (isArray(children)) {
1796
+ const nextLevelOptions = {
1797
+ ...options,
1798
+ parents: [...options.parents, row],
1799
+ depth: options.depth + 1
1800
+ };
1801
+ for (const child of children) preImpl$1(child, callback, nextLevelOptions);
1802
+ }
1803
+ }
1804
+ function postImpl$1(row, callback, options) {
1805
+ const children = row[getFinalChildrenKey(row, options, options)];
1806
+ if (isArray(children)) {
1807
+ const nextLevelOptions = {
1808
+ ...options,
1809
+ parents: [...options.parents, row],
1810
+ depth: options.depth + 1
1811
+ };
1812
+ for (const child of children) postImpl$1(child, callback, nextLevelOptions);
1813
+ }
1814
+ callback(row, options);
1815
+ }
1816
+ function breadthImpl$1(row, callback, options) {
1817
+ const queue = [{
1818
+ queueRow: row,
1819
+ queueOptions: options
1820
+ }];
1821
+ const runQueue = () => {
1822
+ if (queue.length === 0) return;
1823
+ const { queueRow, queueOptions } = queue.shift();
1824
+ const children = queueRow[getFinalChildrenKey(queueRow, queueOptions, queueOptions)];
1825
+ if (isArray(children)) {
1826
+ const nextLevelOptions = {
1827
+ ...queueOptions,
1828
+ parents: [...queueOptions.parents, queueRow],
1829
+ depth: queueOptions.depth + 1
1830
+ };
1831
+ const subQueueItems = children.map((queueRow$1) => ({
1832
+ queueRow: queueRow$1,
1833
+ queueOptions: nextLevelOptions
1834
+ }));
1835
+ queue.push(...subQueueItems);
1836
+ }
1837
+ callback(queueRow, queueOptions);
1838
+ runQueue();
1839
+ };
1840
+ runQueue();
1841
+ }
1842
+ /**
1843
+ * 遍历树节点
1844
+ *
1845
+ * @param tree 树结构数据
1846
+ * @param callback 回调函数
1847
+ * @param options 配置项
1848
+ * @example
1849
+ * ```ts
1850
+ * const tree = [{ id: 1, children: [{ id: 2 }] }];
1851
+ * const ids: number[] = [];
1852
+ * treeForEach(tree, (node) => ids.push(node.id));
1853
+ * // ids: [1, 2] (pre-order default)
1854
+ * ```
1855
+ */
1856
+ function treeForEach(tree, callback, options = {}) {
1857
+ const { childrenKey = "children", strategy = "pre", getChildrenKey } = options;
1858
+ const traversalMethod = strategies$1[strategy];
1859
+ const innerOptions = {
1860
+ childrenKey,
1861
+ depth: 0,
1862
+ parents: [],
1863
+ getChildrenKey
1864
+ };
1865
+ if (isArray(tree)) for (const row of tree) traversalMethod(row, callback, innerOptions);
1866
+ else traversalMethod(tree, callback, innerOptions);
1867
+ }
1868
+
1869
+ //#endregion
1870
+ //#region src/utils/tree/treeMap.ts
1871
+ const strategies = {
1872
+ pre: preImpl,
1873
+ post: postImpl,
1874
+ breadth: breadthImpl
1875
+ };
1876
+ function preImpl(row, callback, options) {
1877
+ const finalChildrenKey = getFinalChildrenKey(row, options, options);
1878
+ const result = callback(row, options);
1879
+ const children = row[finalChildrenKey];
1880
+ let newChildren;
1881
+ if (isArray(children)) {
1882
+ const nextLevelOptions = {
1883
+ ...options,
1884
+ parents: [...options.parents, row],
1885
+ depth: options.depth + 1
1886
+ };
1887
+ newChildren = children.map((c) => preImpl(c, callback, nextLevelOptions));
1888
+ }
1889
+ return {
1890
+ ...result,
1891
+ [finalChildrenKey]: newChildren
1892
+ };
1893
+ }
1894
+ function postImpl(row, callback, options) {
1895
+ const finalChildrenKey = getFinalChildrenKey(row, options, options);
1896
+ const children = row[finalChildrenKey];
1897
+ let newChildren;
1898
+ if (isArray(children)) {
1899
+ const nextLevelOptions = {
1900
+ ...options,
1901
+ parents: [...options.parents, row],
1902
+ depth: options.depth + 1
1903
+ };
1904
+ newChildren = children.map((c) => postImpl(c, callback, nextLevelOptions));
1905
+ }
1906
+ return {
1907
+ ...callback(row, options),
1908
+ [finalChildrenKey]: newChildren
1909
+ };
1910
+ }
1911
+ function breadthImpl(row, callback, options) {
1912
+ const queue = [{
1913
+ queueRow: row,
1914
+ queueOptions: options
1915
+ }];
1916
+ const cache = /* @__PURE__ */ new WeakMap();
1917
+ const childrenKeyCache = /* @__PURE__ */ new WeakMap();
1918
+ let result;
1919
+ const runQueue = () => {
1920
+ if (queue.length === 0) return result;
1921
+ const { queueRow, queueOptions } = queue.shift();
1922
+ const finalChildrenKey = getFinalChildrenKey(queueRow, queueOptions, queueOptions);
1923
+ const children = queueRow[finalChildrenKey];
1924
+ if (isArray(children)) {
1925
+ const nextLevelOptions = {
1926
+ ...queueOptions,
1927
+ parents: [...queueOptions.parents, queueRow],
1928
+ depth: queueOptions.depth + 1
1929
+ };
1930
+ const subQueueItems = children.map((queueRow$1) => ({
1931
+ queueRow: queueRow$1,
1932
+ queueOptions: nextLevelOptions
1933
+ }));
1934
+ queue.push(...subQueueItems);
1935
+ }
1936
+ const res = callback(queueRow, queueOptions);
1937
+ cache.set(queueRow, res);
1938
+ childrenKeyCache.set(queueRow, finalChildrenKey);
1939
+ const parent = arrayLast(queueOptions.parents);
1940
+ if (parent) {
1941
+ const newParent = cache.get(parent);
1942
+ const parentChildrenKey = childrenKeyCache.get(parent);
1943
+ if (newParent && parentChildrenKey) if (newParent[parentChildrenKey]) newParent[parentChildrenKey].push(res);
1944
+ else newParent[parentChildrenKey] = [res];
1945
+ }
1946
+ if (queueOptions.depth === 0) result = res;
1947
+ return runQueue();
1948
+ };
1949
+ return runQueue();
1950
+ }
1951
+ function treeMap(tree, callback, options = {}) {
1952
+ const { childrenKey = "children", strategy = "pre", getChildrenKey } = options;
1953
+ const traversalMethod = strategies[strategy];
1954
+ const innerOptions = {
1955
+ childrenKey,
1956
+ depth: 0,
1957
+ parents: [],
1958
+ getChildrenKey
1959
+ };
1960
+ return isArray(tree) ? tree.map((row) => traversalMethod(row, callback, innerOptions)) : traversalMethod(tree, callback, innerOptions);
1961
+ }
1962
+
1963
+ //#endregion
1964
+ //#region src/utils/tree/rowsToTree.ts
1965
+ /**
1966
+ * 行结构 转 树结构
1967
+ * - 将平铺的数组转换为树形结构
1968
+ *
1969
+ * @param rows 行数据数组
1970
+ * @param options 配置项
1971
+ * @returns 树结构数组
1972
+ * @example
1973
+ * ```ts
1974
+ * const rows = [
1975
+ * { id: 1, parentId: null },
1976
+ * { id: 2, parentId: 1 },
1977
+ * ];
1978
+ * rowsToTree(rows);
1979
+ * // [{ id: 1, parentId: null, children: [{ id: 2, parentId: 1 }] }]
1980
+ * ```
1981
+ */
1982
+ function rowsToTree(rows, options) {
1983
+ const { parentIdKey = "parentId", rowKey = "id", childrenKey = "children" } = options || {};
1984
+ const result = [];
1985
+ const map = /* @__PURE__ */ new Map();
1986
+ for (const row of rows) {
1987
+ const id = row[rowKey];
1988
+ if (!map.get(id)) map.set(id, row);
1989
+ }
1990
+ for (const row of rows) {
1991
+ const parentId = row[parentIdKey];
1992
+ const parent = map.get(parentId);
1993
+ if (!parent || !parentId) {
1994
+ result.push(row);
1995
+ continue;
1996
+ }
1997
+ const siblings = parent[childrenKey];
1998
+ if (isNull(siblings) || isUndefined(siblings)) parent[childrenKey] = [row];
1999
+ else if (Array.isArray(siblings)) siblings.push(row);
2000
+ else {
2001
+ const message = `The key "${childrenKey.toString()}" in parent item is not an array.`;
2002
+ throw new Error(message);
2003
+ }
2004
+ }
2005
+ return result;
2006
+ }
2007
+
2008
+ //#endregion
2009
+ //#region src/utils/tree/treeToRows.ts
2010
+ /**
2011
+ * 树结构 转 行结构
2012
+ * - 将树形结构扁平化为数组
2013
+ *
2014
+ * @param tree 树结构数据 (单个节点或节点数组)
2015
+ * @param options 配置项
2016
+ * @returns 扁平化后的数组
2017
+ * @example
2018
+ * ```ts
2019
+ * const tree = [{ id: 1, children: [{ id: 2 }] }];
2020
+ * treeToRows(tree);
2021
+ * // [{ id: 1, children: undefined }, { id: 2, children: undefined }]
2022
+ * ```
2023
+ */
2024
+ function treeToRows(tree, options = {}) {
2025
+ const { childrenKey = "children" } = options;
2026
+ const result = [];
2027
+ if (!tree) return result;
2028
+ treeForEach(tree, (t) => result.push({
2029
+ ...t,
2030
+ [childrenKey]: void 0
2031
+ }), options);
2032
+ return result;
2033
+ }
2034
+
2035
+ //#endregion
2036
+ export { arrayCounting as $, toMathEvaluate as A, isEnumeration as At, arrayZipToObject as B, isBigInt as Bt, mapEntries as C, isMap as Ct, enumEntries as D, isFalsyLike as Dt, enumKeys as E, isFalsy as Et, isTablet as F, isFunction as Ft, arrayReplace as G, arrayZip as H, isTypedArray as Ht, isIOSMobile as I, isGeneratorFunction as It, arrayLast as J, arrayPick as K, isMobile as L, isBoolean as Lt, toMathBignumber as M, isClass as Mt, stringToNumber as N, isAsyncFunction as Nt, cloneDeep as O, isError as Ot, to as P, isAsyncGeneratorFunction as Pt, arrayDifference as Q, isBrowser as R, isBlob as Rt, objectAssign as S, isNull as St, enumValues as T, isIterable as Tt, arraySplit as U, isAbortSignal as Ut, arrayUnzip as V, isArray as Vt, arrayReplaceMove as W, arrayFork as X, arrayIntersection as Y, arrayFirst as Z, objectPick as _, isInteger as _t, treeFind as a, isUndefined as at, objectInvert as b, isNumber as bt, stringTruncate as c, isWeakSet as ct, stringToPosix as d, isReadableStream as dt, arrayCompete as et, stringToJson as f, isPromise as ft, objectValues as g, isInfinityLike as gt, stringInitialCase as h, isInfinity as ht, treeForEach as i, isURLSearchParams as it, toMathDecimal as j, isDate as jt, isWithinInterval as k, isEqual as kt, stringTrim as l, isRegExp as lt, stringReplace as m, isObject as mt, rowsToTree as n, isWindow as nt, treeFilter as o, isSymbol as ot, stringTemplate as p, isPromiseLike as pt, arrayMerge as q, treeMap as r, isWebSocket as rt, getTimeZone as s, isSet as st, treeToRows as t, arrayCast as tt, stringToValues as u, isString as ut, objectOmit as v, isNaN as vt, objectEntries as w, isWeakMap as wt, objectCrush as x, isPositiveInteger as xt, objectKeys as y, isNegativeInteger as yt, isWebWorker as z, isFile as zt };
2037
+ //# sourceMappingURL=utils-RGh-N7TJ.js.map