common.uts
26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
import type { ComponentPublicInstance, Ref } from "vue";
/**
* ✅ 可空任意类型(简化 any | null 的写法)
* @example const value: AnyOrNull = someValue;
*/
export type AnyOrNull = any | null;
/**
* ✅ 可空 UTSJSONObject 类型(简化 UTSJSONObject | null 的写法)
* @example const obj: ObjOrNull = someObject;
*/
export type ObjOrNull = UTSJSONObject | null;
/**
* ✅ 可空字符串类型(简化 string | null 的写法)
* @example const str: StrOrNull = someString;
*/
export type StrOrNull = string | null;
/**
* ✅ 可空任意数组类型(简化 any[] | null 的写法)
* @example const arr: AnyArrOrNull = someArray;
*/
export type AnyArrOrNull = any[] | null;
export type NumOrNull = number | null;
/**
* ✅ 空对象常量
* @example const data = EMPTY_OBJECT;
*/
export const EMPTY_OBJECT: UTSJSONObject = {} as UTSJSONObject;
/**
* ✅ 安全转换为字符串
* @param value 要转换的值
* @param defaultValue 默认值,默认为空字符串
* @returns 字符串,如果值为 null/undefined 则返回默认值
* @example toStr(value)
* @example toStr(value, "default")
*/
export function toStr(value: any | null, defaultValue: string = ""): string {
if (value == null) {
return defaultValue;
}
return `${value}`;
}
/**
* ✅ 判断字符串是否为空(null、undefined 或空字符串)
* @param value 要检查的字符串
* @returns true 表示为空,false 表示有值
* @example isEmptyStr(null) // true
* @example isEmptyStr("") // true
* @example isEmptyStr("hello") // false
*/
export function isEmptyStr(value: string | null | undefined): boolean {
return value == null || value === "";
}
/**
* ✅ 判断字符串是否非空(有实际值)
* @param value 要检查的字符串
* @returns true 表示有值,false 表示为空
* @example isNotEmptyStr(null) // false
* @example isNotEmptyStr("") // false
* @example isNotEmptyStr("hello") // true
*/
export function isNotEmptyStr(value: string | null | undefined): boolean {
return value != null && value !== "";
}
/**
* ✅ 安全转换为布尔值
* @param value 要转换的值
* @param defaultValue 默认值,默认为 false
* @returns 布尔值
* @example toBool(true) // true
* @example toBool("true") // true
* @example toBool(1) // true
* @example toBool(null) // false
*/
export function toBool(value: any | null, defaultValue: boolean = false): boolean {
if (value == null) {
return defaultValue;
}
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'string') {
const lower = value.toLowerCase();
return lower === 'true' || lower === '1' || lower === 'yes';
}
if (typeof value === 'number') {
return value != 0;
}
return defaultValue;
}
/**
* ✅ 安全转换为数字
* @param value 要转换的值
* @param defaultValue 默认值,默认为 0
* @returns 数字,如果值为 null/undefined 或无法转换则返回默认值
* @example toNum(123) // 123
* @example toNum("456") // 456
* @example toNum(null) // 0
* @example toNum("abc", -1) // -1
*/
export function toNum(value: any | null, defaultValue: number = 0): number {
if (value == null) {
return defaultValue;
}
if (typeof value === 'number') {
return value;
}
if (typeof value === 'string') {
// ✅ UTS 不支持 Number() 构造函数,使用 parseFloat
const num = parseFloat(value);
return isNaN(num) ? defaultValue : num;
}
return defaultValue;
}
/**
* ✅ 安全转换为字符串数组
* @param value 要转换的值(可能是字符串数组、JSON 字符串或其他类型)
* @param defaultValue 默认值,默认为空数组
* @returns 字符串数组,如果值为 null/undefined 或无法转换则返回默认值
* @example toStrArr(["a", "b"]) // ["a", "b"]
* @example toStrArr('["a","b"]') // ["a", "b"]
* @example toStrArr(null) // []
*/
export function toStrArr(value: any | null, defaultValue: string[] = []): string[] {
if (value == null) {
return defaultValue;
}
// 如果已经是数组
if (Array.isArray(value)) {
// 确保每个元素都是字符串
const result: string[] = [];
for (let i = 0; i < value.length; i++) {
const item = value[i];
if (item != null) {
result.push(`${item}`);
}
}
return result;
}
// 如果是字符串,尝试解析为 JSON 数组
if (typeof value === 'string') {
try {
const trimmed = value.trim();
if (trimmed.startsWith('[')) {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
const result: string[] = [];
for (let i = 0; i < parsed.length; i++) {
const item = parsed[i];
if (item != null) {
result.push(`${item}`);
}
}
return result;
}
}
} catch {
// 解析失败,返回默认值
}
}
return defaultValue;
}
/**
* ✅ 安全转换为 UTSJSONObject 数组
* @param value 要转换的值(可能是对象数组、JSON 字符串或其他类型)
* @param defaultValue 默认值,默认为空数组
* @returns UTSJSONObject 数组,如果值为 null/undefined 或无法转换则返回默认值
* @example toObjArr([{a:1}, {b:2}]) // [{a:1}, {b:2}]
* @example toObjArr('[{"a":1}]') // [{a:1}]
* @example toObjArr(null) // []
*/
export function toObjArr(value: any | null, defaultValue: UTSJSONObject[] = []): UTSJSONObject[] {
if (value == null) {
return defaultValue;
}
// 如果已经是数组
if (Array.isArray(value)) {
const result: UTSJSONObject[] = [];
for (let i = 0; i < value.length; i++) {
const item = value[i];
if (item != null && typeof item === 'object') {
result.push(item as UTSJSONObject);
}
}
return result;
}
// 如果是字符串,尝试解析为 JSON 数组
if (typeof value === 'string') {
try {
const trimmed = value.trim();
if (trimmed.startsWith('[')) {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
const result: UTSJSONObject[] = [];
for (let i = 0; i < parsed.length; i++) {
const item = parsed[i];
if (item != null && typeof item === 'object') {
result.push(item as UTSJSONObject);
}
}
return result;
}
}
} catch {
// 解析失败,返回默认值
}
}
return defaultValue;
}
/**
* ✅ 将对象转换为 Map
* @param obj 要转换的对象
* @returns Map<string, any>,如果对象为 null/undefined 则返回空 Map
* @example toMap({a: 1, b: 2}) // Map {"a" => 1, "b" => 2}
* @example toMap(null) // Map {}
*/
export function toMap(obj: any | null): Map<string, any> {
const map = new Map<string, any>();
if (obj == null || typeof obj !== 'object') {
return map;
}
// ✅ UTS 限制:无法动态遍历对象键,采用 JSON 序列化后正则提取键名
try {
const jsonStr = JSON.stringify(obj);
// 使用正则表达式提取所有键名
const keyRegex = /"([^"]+)"\s*:/g;
const keys: string[] = [];
let match: RegExpExecArray | null = keyRegex.exec(jsonStr);
while (match != null) {
const key = match[1];
if (key != null) {
keys.push(key);
}
match = keyRegex.exec(jsonStr);
}
// 去重
const uniqueKeys: string[] = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
let exists = false;
for (let j = 0; j < uniqueKeys.length; j++) {
if (uniqueKeys[j] === key) {
exists = true;
break;
}
}
if (!exists) {
uniqueKeys.push(key);
}
}
// 根据键名提取值
const parsed = JSON.parse(jsonStr) as UTSJSONObject;
for (let i = 0; i < uniqueKeys.length; i++) {
const key = uniqueKeys[i];
const value = parsed[key];
if (value != null) {
map.set(key, value);
}
}
} catch {
// 解析失败,返回空 Map
}
return map;
}
/**
* ✅ 安全转换为 UTSJSONObject
* @param value 要转换的值
* @returns UTSJSONObject,如果值为 null/undefined 则返回 EMPTY_OBJECT
* @example toObj(response.data)
*/
export function toObj(value: any | null, fallback: UTSJSONObject = EMPTY_OBJECT): UTSJSONObject {
if (value == null) {
return fallback;
}
if (typeof value === 'object') {
return value as UTSJSONObject;
}
// 如果是字符串,尝试解析
if (typeof value === 'string') {
try {
const trimmed = value.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
return JSON.parse(trimmed) as UTSJSONObject;
}
} catch {
// 解析失败,返回 fallback
}
}
return fallback;
}
/**
* 检查值是否为数组
* @example isArray([1, 2, 3]) // true
* @example isArray('123') // false
*/
export function isArray(value: any): boolean {
return Array.isArray(value);
}
/**
* 检查值是否为对象
* @example isObject({}) // true
* @example isObject([]) // false
*/
export function isObject(value: any): boolean {
return typeof value === "object" && !Array.isArray(value) && !isNull(value);
}
/**
* 检查值是否为字符串
* @example isString('abc') // true
* @example isString(123) // false
*/
export function isString(value: any): boolean {
return typeof value === "string";
}
/**
* 检查值是否为数字
* @example isNumber(123) // true
* @example isNumber('123') // false
*/
export function isNumber(value: any): boolean {
return typeof value === "number" && !isNaN(value);
}
/**
* 检查值是否为布尔值
* @example isBoolean(true) // true
* @example isBoolean(1) // false
*/
export function isBoolean(value: any): boolean {
return typeof value === "boolean";
}
/**
* 检查值是否为函数
* @example isFunction(() => {}) // true
* @example isFunction({}) // false
*/
export function isFunction(value: any): boolean {
return typeof value === "function";
}
/**
* 检查值是否为 null
* @example isNull(null) // true
* @example isNull(undefined) // true
*/
export function isNull(value?: any | null): boolean {
// #ifdef APP
return value == null;
// #endif
// #ifndef APP
return value == null || value == undefined;
// #endif
}
/**
* 检查值是否为空
* @example isEmpty([]) // true
* @example isEmpty('') // true
* @example isEmpty({}) // true
*/
export function isEmpty(value: any): boolean {
if (isArray(value)) {
// ✅ UTS 避免 Number === Int 比较,使用 ==
return (value as any[]).length == 0;
}
if (isString(value)) {
return value == "";
}
if (isObject(value)) {
// ✅ UTS 避免 Number === Int 比较,使用 ==
return keys(value).length == 0;
}
return false;
}
/**
* 安全地从对象中获取字符串属性值
* @param obj 源对象
* @param key 属性键名
* @param defaultValue 默认值,默认为空字符串
* @returns 属性值的字符串形式,如果对象或属性为 null/undefined 则返回默认值
* @example
* getStringProp(user, "userid", "") // 返回 user.userid 的字符串形式或 ""
* getStringProp(info, "deviceId", "unknown") // 返回 info.deviceId 或 "unknown"
*/
export function getStringProp(obj: any | null, key: string, defaultValue: string = ""): string {
if (obj == null || typeof obj !== "object") {
return defaultValue;
}
const value = (obj as UTSJSONObject)[key];
if (value == null) {
return defaultValue;
}
return `${value}`;
}
/**
* 返回对象的所有键名
* @example keys({a: 1, b: 2}) // ['a', 'b']
*/
export const nullValues = [null, ""];
export function keys(object: any): string[] {
if (!isObject(object)) {
return [];
}
// 避免 Android 上 UTSJSONObject.keys 返回 UTSArray<kotlin.String> 与 string[](java.lang.String)声明不一致
const out: string[] = [];
const o = object as UTSJSONObject;
for (const k in o) {
if (k != "") {
out.push("" + k);
}
}
return out;
}
/**
* 格式化日期时间
*/
export function convertDateTimeFormat(date: Date, separator: string): string {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
// 模板字符串在 Android 侧常为 kotlin.String,与对外 string(java.lang.String)返回值不一致
return "" + year + separator + month + separator + day + " " + hours + ":" + minutes + ":" + seconds;
}
/**
* 生成 UUID
* @example getUUID() // "123e4567-e89b-12d3-a456-426614174000"
*/
export function getUUID(): string {
let uuidStr = "";
let i: number;
let random: number;
for (i = 0; i < 36; i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
uuidStr += "-";
} else if (i == 14) {
uuidStr += "4";
} else if (i == 19) {
random = (Math.random() * 16) | 0;
uuidStr += ((random & 0x3) | 0x8).toString(16);
} else {
random = (Math.random() * 16) | 0;
uuidStr += random.toString(16);
}
}
return "" + uuidStr;
}
/**
* 返回数组的第一个元素
* @example first([1, 2, 3]) // 1
* @example first([]) // null
*/
export function first<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[0] : null;
}
/**
* 返回数组的最后一个元素
* @example last([1, 2, 3]) // 3
* @example last([]) // null
*/
export function last<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[array.length - 1] : null;
}
/**
* 截取数组的一部分
* @example slice([1, 2, 3], 1) // [2, 3]
* @example slice([1, 2, 3], 1, 2) // [2]
*/
export function slice<T>(array: T[], start: number = 0, end: number = array.length): T[] {
if (!isArray(array)) return [];
const result: T[] = [];
for (let i = start; i < end && i < array.length; i++) {
result.push(array[i]);
}
return result;
}
/**
* 检查对象是否包含指定属性
* @example has({a: 1}, 'a') // true
* @example has({a: 1}, 'b') // false
*/
export function has(object: any, key: string): boolean {
return keys(object).includes(key);
}
/**
* 获取对象的属性值
* @example get({a: {b: 1}}, 'a.b') // 1
* @example get({a: {b: 1}}, 'a.c', 'default') // 'default'
*/
export function get(object: any, path: string, defaultValue: any | null = null): any | null {
if (isNull(object)) {
return defaultValue;
}
// getAny 在 Android 侧参数需 kotlin.String;入参 path 常为 java.lang.String,用模板桥接
const pathKey = `${path}`;
const value = new UTSJSONObject(object).getAny(pathKey);
if (isNull(value)) {
return defaultValue;
}
return value;
}
/**
* 获取 UTSJSONObject 类型的属性值
* @example getAsObject(obj, 'key') // UTSJSONObject | null
*/
export function getAsObject(object: any, path: string): UTSJSONObject | null {
const value = get(object, path)
return value != null ? (value as UTSJSONObject) : null
}
/**
* 设置对象的属性值
* @example set({a: 1}, 'b', 2) // {a: 1, b: 2}
*/
export function set(object: any, key: string, value: any | null): void {
(object as UTSJSONObject)[key] = value;
}
/**
* 遍历数组并返回新数组
* @example map([1, 2, 3], x => x * 2) // [2, 4, 6]
*/
export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U): U[] {
const result: U[] = [];
if (!isArray(array)) return result;
for (let i = 0; i < array.length; i++) {
const element = array[i];
result.push(iteratee(element, i));
}
return result;
}
/**
* 将数组归约为单个值
* @example reduce([1, 2, 3], (sum, n) => sum + n, 0) // 6
*/
export function reduce<T, U>(
array: T[],
iteratee: (accumulator: U, value: T, index: number) => U,
initialValue: U
): U {
if (!isArray(array)) return initialValue;
let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) {
const element = array[i];
accumulator = iteratee(accumulator, element, i);
}
return accumulator;
}
/**
* 检查数组中的所有元素是否都满足条件
* @example every([2, 4, 6], x => x % 2 == 0) // true
*/
export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return true;
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (!predicate(element, i)) {
return false;
}
}
return true;
}
/**
* 检查数组中是否有元素满足条件
* @example some([1, 2, 3], x => x > 2) // true
*/
export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return false;
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (predicate(element, i)) {
return true;
}
}
return false;
}
/**
* 创建去重后的数组
* @example uniq([1, 2, 2, 3]) // [1, 2, 3]
*/
export function uniq<T>(array: T[]): T[] {
if (!isArray(array)) return [];
const result: T[] = [];
const seen = new Map<T, boolean>();
for (const item of array) {
const key = item;
if (!seen.has(item)) {
seen.set(key, true);
result.push(item);
}
}
return result;
}
/**
* 将数组扁平化一层
* @example flatten([1, [2, 3], 4]) // [1, 2, 3, 4]
*/
export function flatten(array: any[]): any[] {
if (!isArray(array)) return [];
const result: any[] = [];
for (const item of array) {
if (isArray(item)) {
result.push(...(item as any[]));
} else {
result.push(item);
}
}
return result;
}
/**
* 将数组完全扁平化
* @example flattenDeep([1, [2, [3, [4]]]]) // [1, 2, 3, 4]
*/
export function flattenDeep(array: any[]): any[] {
if (!isArray(array)) return [];
const result: any[] = [];
for (const item of array) {
if (isArray(item)) {
result.push(...flattenDeep(item as any[]));
} else {
result.push(item);
}
}
return result;
}
/**
* 对数组进行排序
* @example sort([3, 1, 2]) // [1, 2, 3]
* @example sort(['c', 'a', 'b'], 'desc') // ['c', 'b', 'a']
*/
export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] {
const result = [...array];
return result.sort((a, b) => {
if (typeof a === "number" && typeof b === "number") {
return order == "asc" ? a - b : b - a;
}
if (typeof a === "string" && typeof b === "string") {
return order == "asc" ? a.localeCompare(b) : b.localeCompare(a);
}
return 0;
});
}
/**
* 根据对象属性对数组进行排序
* @example orderBy([{age: 30}, {age: 20}], 'age') // [{age: 20}, {age: 30}]
*/
export function orderBy<T>(array: T[], key: string, order: "asc" | "desc" = "asc"): T[] {
if (!isArray(array)) return [];
const result = [...array];
result.sort((a, b) => {
const valueA = get(a as any, key) as number;
const valueB = get(b as any, key) as number;
if (order == "asc") {
return valueA > valueB ? 1 : -1;
} else {
return valueA < valueB ? 1 : -1;
}
});
return result;
}
/**
* 根据对象属性对数组进行分组
* @example groupBy([{type: 'a'}, {type: 'b'}, {type: 'a'}], 'type') // {a: [{type: 'a'}, {type: 'a'}], b: [{type: 'b'}]}
*/
export function groupBy<T>(array: T[], key: string) {
if (!isArray(array)) return {};
const result = {};
for (const item of array) {
let value = get(item as any, key)!;
if (typeof value === "number") {
value = value.toString();
}
if (typeof value === "string") {
if (!isArray(result[value])) {
result[value] = new Array<T>();
}
(result[value] as T[]).push(item);
}
}
return result;
}
/**
* 将多个对象的属性合并到一个对象中
* @example assign({a: 1}, {b: 2}) // {a: 1, b: 2}
*/
export function assign(...items: any[]) {
// @ts-ignore
return UTSJSONObject.assign(...items.map((item) => item as UTSJSONObject));
}
/**
* 合并多个对象(支持 null 值,自动忽略)
* @param items 要合并的对象列表
* @returns 合并后的新对象
* @example merge({a: 1}, null, {b: 2}) // {a: 1, b: 2}
*/
export function merge(...items: Array<any | null>): UTSJSONObject {
// 创建目标对象
const target: UTSJSONObject = {}
// 逐个合并源对象
for (let i = 0; i < items.length; i++) {
const source = items[i]
if (source != null) {
const sourceObj = source as UTSJSONObject
for (const key in sourceObj) {
target[key] = sourceObj[key]
}
}
}
return target
}
/**
* 获取数组中指定索引的元素
* @example nth([1, 2, 3], 1) // 2
* @example nth([1, 2, 3], -1) // 3
*/
export function nth<T>(array: T[], index: number): null | T {
if (index >= 0) {
return array[index];
}
return array[array.length + index];
}
/**
* 从数组中移除指定的值
* @example pull([1, 2, 3, 1, 2, 3], 1, 2) // [3, 3]
*/
export function pull<T>(array: T[], ...values: T[]): T[] {
if (!isArray(array)) return [];
return array.filter((item) => !values.includes(item));
}
/**
* 从数组中移除满足条件的元素
* @example remove([1, 2, 3, 4], x => x % 2 == 0) // [1, 3]
*/
export function remove<T>(array: T[], predicate: (value: T, index: number) => boolean): T[] {
if (!isArray(array)) return [];
const result: T[] = [];
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (!predicate(element, i)) {
result.push(element);
}
}
return result;
}
/**
* 遍历数组
* @example forEach([1, 2, 3], x => console.log(x))
*/
export function forEach<T>(data: T[], iteratee: (value: T, index: number) => void): void {
if (isArray(data)) {
const array = data as T[];
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (element != null) {
iteratee(element, i);
}
}
}
}
/**
* 查找数组中第一个满足条件的元素
* @example find([1, 2, 3, 4], x => x > 2) // 3
*/
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): null | T {
if (!isArray(array)) return null;
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (predicate(element, i)) {
return element;
}
}
return null;
}
/**
* 遍历对象
* @example forInObject({a: 1, b: 2}, (value, key) => console.log(key, value))
*/
export function forInObject(data: any, iteratee: (value: any, key: string) => void): void {
if (isObject(data)) {
const objKeys = keys(data);
for (const key of objKeys) {
iteratee(get(data, key)!, key);
}
}
}
/**
* 对象转数组
* @example toArray({a: 1, b: 2}, (value, key) => ({key, value})) // [{key: 'a', value: 1}, {key: 'b', value: 2}]
*/
export function toArray<T>(data: any, iteratee: (value: any, key: string) => T): T[] {
const result: T[] = [];
if (isObject(data)) {
forInObject(data, (value, key) => {
result.push(iteratee(value, key));
});
}
return result;
}
/**
* 创建一个防抖函数,在指定延迟后执行函数,如果在延迟期间再次调用则重新计时
* @example debounce(() => console.log('执行'), 300)
*/
export function debounce(func: () => void, delay: number): () => number {
let timeoutId = 0;
return function (): number {
// 清除之前的定时器
if (timeoutId != 0) {
clearTimeout(timeoutId);
}
// 设置新的定时器
timeoutId = setTimeout(() => {
func();
timeoutId = 0;
}, delay);
return timeoutId;
};
}
/**
* 创建一个节流函数,在指定时间间隔内只会执行一次
* @example
* const throttled = throttle(() => console.log('执行'), 300)
* throttled()
*/
export function throttle(func: () => void, delay: number): () => number {
let timeoutId: number = 0;
let lastExec: number = 0;
return function (): number {
const now: number = Date.now();
// 如果距离上次执行已超过delay,则立即执行
if (now - lastExec >= delay) {
func();
lastExec = now;
return 0;
}
// 否则在剩余时间后执行
if (timeoutId != 0) {
clearTimeout(timeoutId);
}
const remaining: number = delay - (now - lastExec);
// @ts-ignore
timeoutId = setTimeout(() => {
func();
lastExec = Date.now();
timeoutId = 0;
}, remaining);
return timeoutId;
};
}
/**
* 生成指定范围内的随机数
* @example random(1, 10) // 随机生成1到10之间的整数
*/
export function random(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* 将base64转换为blob
* @param data base64数据
* @returns blob数据
*/
export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob {
// #ifdef H5
const bytes = window.atob(data.split(",")[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], { type });
// #endif
}
/**
* 检查两个值是否相等
* @param a 值1
* @param b 值2
* @returns 是否相等
*/
export function isEqual(a: any, b: any): boolean {
if (isObject(a) && isObject(b)) {
return isEqual(JSON.stringify(a), JSON.stringify(b));
} else if (isArray(a) && isArray(b)) {
return isEqual(JSON.stringify(a), JSON.stringify(b));
}
return a == b;
}
/**
* 替换字符串中的所有匹配项
* @param text 原始字符串
* @param find 要查找的字符串
* @param replace 替换后的字符串
* @returns 替换后的字符串
*/
export function replaceAll(text: string, find: string, replace: string): string {
if (text.indexOf(find) == -1) {
return text;
}
const parts = text.split(find);
let res = "";
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
res = res + part;
if (i < parts.length - 1) {
res = res + replace;
}
}
return res;
}
/**
* 深拷贝对象
* @param obj 要拷贝的对象
* @returns 拷贝后的对象
*/
export function deepClone<T>(obj: any): null | T {
// UTS 要求返回类型明确包含 null
if (obj == null) {
return null;
}
if (typeof obj === "object") {
return JSON.parse<T>(JSON.stringify(obj));
}
return obj as T;
}
/**
* 安全调用组件方法(自动处理 Ref 解包和 null 检查)
* @param componentRef 组件引用(可以是 Ref 或直接的值)
* @param methodName 方法名
* @param args 方法参数(可选)
* @example callComponentMethod(stepRef, 'close')
* @example callComponentMethod(payRef, 'open', param1, param2)
*/
export function callComponentMethod(
componentRef: Ref<any> | any,
methodName: string,
...args: any[]
): void {
// 自动解包 Ref
const target = (componentRef as Ref<any>).value != null
? (componentRef as Ref<any>).value
: componentRef;
if (target == null) {
console.warn(`[callComponentMethod] 组件引用为空,无法调用方法: ${methodName}`);
return;
}
try {
// ✅ 使用 $callMethod 调用组件方法
(target as ComponentPublicInstance).$callMethod(methodName, ...args);
} catch (e) {
console.error(`[callComponentMethod] 调用方法失败: ${methodName}`, e);
}
}