@zwa73/utils 1.0.60 → 1.0.62

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.
Files changed (42) hide show
  1. package/dist/UtilCodecs.d.ts +16 -16
  2. package/dist/UtilCodecs.js +16 -16
  3. package/dist/UtilCom.d.ts +22 -25
  4. package/dist/UtilCom.js +35 -38
  5. package/dist/UtilDecorators.d.ts +15 -8
  6. package/dist/UtilDecorators.js +79 -25
  7. package/dist/UtilFP.d.ts +46 -0
  8. package/dist/UtilFP.js +52 -0
  9. package/dist/UtilFfmpegTools.d.ts +30 -30
  10. package/dist/UtilFfmpegTools.js +32 -32
  11. package/dist/UtilFileTools.d.ts +30 -35
  12. package/dist/UtilFileTools.js +17 -18
  13. package/dist/UtilFunctions.d.ts +37 -78
  14. package/dist/UtilFunctions.js +27 -62
  15. package/dist/UtilInterfaces.d.ts +26 -11
  16. package/dist/UtilInterfaces.js +12 -3
  17. package/dist/UtilLogger.d.ts +55 -55
  18. package/dist/UtilLogger.js +55 -55
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.js +1 -0
  21. package/dist/test/composeTest.d.ts +26 -0
  22. package/dist/test/composeTest.js +50 -0
  23. package/dist/test/importtest.d.ts +1 -0
  24. package/dist/test/importtest.js +4 -0
  25. package/dist/test/test.js +5 -3
  26. package/package.json +1 -1
  27. package/src/UtilClass.ts +1051 -1051
  28. package/src/UtilCodecs.ts +117 -117
  29. package/src/UtilCom.ts +171 -174
  30. package/src/UtilDecorators.ts +174 -116
  31. package/src/UtilFP.ts +98 -0
  32. package/src/UtilFfmpegTools.ts +271 -271
  33. package/src/UtilFileTools.ts +231 -236
  34. package/src/UtilFunctions.ts +289 -364
  35. package/src/UtilInterfaces.ts +158 -138
  36. package/src/UtilLogger.ts +386 -386
  37. package/src/index.ts +10 -9
  38. package/src/test/composeTest.ts +50 -0
  39. package/src/test/importtest.ts +5 -0
  40. package/src/test/test.ts +8 -6
  41. package/src/test/test2.ts +2 -3
  42. package/tsconfig.json +2 -7
@@ -1,365 +1,290 @@
1
- import * as crypto from "crypto";
2
- import { ComposedClass, ComposedClassMult, ComposedPartClass as ComposedPartClass, FuncPropNames, JToken, PromiseProcFn, PromiseStat, PromiseVerifyFn } from "./UtilInterfaces";
3
- import * as cp from "child_process";
4
- import { SLogger } from "./UtilLogger";
5
-
6
- /**常用函数 */
7
- export namespace UtilFunc{
8
- /**获取当前时间戳
9
- * number ()
10
- * @returns {number} 时间戳
11
- */
12
- export function getTime(): number {
13
- return new Date().getTime();
14
- }
15
-
16
- /**初始化对象的字段
17
- * void (Object,string,any)
18
- * @param {Record<string,T>} obj - 所要初始化的对象
19
- * @param {string} field - 所要初始化的字段
20
- * @param {T} defaultVal - 默认值
21
- * @returns {T} - 最终值
22
- */
23
- export function initField<T>(
24
- obj: Record<string, T>,
25
- field: string,
26
- defaultVal: T
27
- ): T {
28
- if (!(field in obj)) obj[field] = defaultVal;
29
- return obj[field];
30
- }
31
-
32
- /**生成一串uuid
33
- * string ()
34
- * @returns {string} uuid
35
- */
36
- export function genUUID() {
37
- return crypto.randomBytes(16).toString("hex");
38
- }
39
- /**计算Hash
40
- * string ()
41
- * @param {string} str - 待计算的字符串
42
- * @returns {string} hash
43
- */
44
- export function calcHash(str:string) {
45
- return crypto.createHash('md5').update(str).digest('hex');
46
- }
47
-
48
- /**深克隆 序列化并反序列化
49
- * @template {T} T - JToken类型的泛型
50
- * @param {T} obj - 克隆目标
51
- * @returns {T} 克隆结果
52
- */
53
- export function deepClone<T extends JToken>(obj: T): T {
54
- return JSON.parse(JSON.stringify(obj));
55
- }
56
-
57
- /**是否为安全的数字
58
- * @param {number} num - 所要检测的数字
59
- * @returns {boolean} 是否安全
60
- */
61
- export function isSafeNumber(num: number): boolean {
62
- if (num === undefined || num == null || isNaN(num)) return false;
63
- if(typeof num === 'number') return true;
64
- return false;
65
- }
66
-
67
- /**等待 timeMs 毫秒
68
- * @async
69
- * @param {number} timeMs - 等待的毫秒数
70
- * @returns {Promise<boolean>}
71
- */
72
- export async function sleep(timeMs: number): Promise<boolean> {
73
- return new Promise(function (resolve, rejecte) {
74
- let timer = setTimeout(function () {
75
- resolve(true);
76
- }, timeMs);
77
- });
78
- }
79
-
80
- /**封装的 cp.exec 执行一段指令 指令完成后返回 Promise
81
- * @param {string} command 指令文本
82
- */
83
- export function exec(command: string) {
84
- return new Promise<{ stdout:string, stderr:string }>
85
- ((resolve, reject) => {
86
- cp.exec(command, (error, stdout, stderr) => {
87
- if (error)
88
- reject(error);
89
- else
90
- resolve({ stdout, stderr });
91
- });
92
- });
93
- }
94
-
95
- /**永不完成的Promise单例 */
96
- const NeverResolvedPromise = new Promise(()=>{});
97
- /**获得一个永不完成的Promise单例 */
98
- export function getNeverResolvedPromise<T>():Promise<T>{
99
- return NeverResolvedPromise as Promise<T>;
100
- }
101
-
102
- /**进行中的请求 */
103
- type ProcessingPromise<T> = {
104
- /**主体请求 */
105
- result:T;
106
- /**请求状态 */
107
- stat:PromiseStat|Promise<PromiseStat>;
108
- /**请求下标/序号 */
109
- index:number;
110
- };
111
-
112
- /**重复尝试promise
113
- * @async
114
- * @param {PromiseProcFn<T>} [procFn] - 发起函数
115
- * @param {PromiseVerifyFn<T>} [verifyFn] - 验证函数
116
- * @param {number} [repeatCount] - 重试次数
117
- * @param {number} [repeatTime] - 超时时间/秒 最小为10秒
118
- * @returns {Promise<T|null>} - 结果 null 为全部失败/超时
119
- */
120
- export async function repeatPromise<T>(procFn:PromiseProcFn<T>,verifyFn?:PromiseVerifyFn<T>,
121
- repeatCount:number=3,repeatTime:number=180):Promise<T|null>{
122
-
123
- //计时
124
- const timeflag = "repeatPromise "+UtilFunc.genUUID();
125
- SLogger.time(timeflag);
126
-
127
- //转换为毫秒
128
- const hasRepeatTime = (repeatTime>=10);
129
- if(hasRepeatTime) repeatTime*=1000;
130
-
131
- //验证处理函数
132
- if(verifyFn===undefined)
133
- verifyFn = ()=>"Completed";
134
-
135
- //计时器
136
- let timer:NodeJS.Timer|null = null;
137
- let timerP:Promise<"Timeout">|null=null;
138
- let resolveFn:((value: "Timeout" | PromiseLike<"Timeout">)=>void)|null = null;
139
- /**清理计时器 */
140
- const clearTimer = ()=>{
141
- if(timer!=null)
142
- clearInterval(timer);
143
- if(resolveFn!=null)
144
- resolveFn("Timeout");
145
- timerP=null;
146
- timer=null;
147
- resolveFn=null;
148
- }
149
-
150
- //进行中的请求
151
- const plist:Promise<ProcessingPromise<T>>[] = [];
152
-
153
- //开始处理
154
- try{
155
- for(let i=0;i<repeatCount;){
156
- SLogger.info(`开始第 ${i+1} 次 repeatPromise`);
157
- //创建当前任务
158
- if(plist.length<i+1){
159
- plist.push(procFn().then(result =>
160
- ({result, stat:verifyFn!(result), index:i})));
161
- }
162
-
163
- //创建定时器
164
- if(timerP==null){
165
- timerP = new Promise<"Timeout">(function(resolve, rejecte){
166
- resolveFn = resolve;
167
- timer = setTimeout(()=>resolve("Timeout"),
168
- hasRepeatTime? repeatTime:Infinity);//无限制则无限时间
169
- })
170
- }
171
-
172
- //等待完成
173
- const currObj = await Promise.race([...plist, timerP]);
174
-
175
- //超时处理
176
- if(currObj=="Timeout"){
177
- SLogger.warn(`第 ${i+1} 次 repeatPromise 超时 ${repeatTime} ms 开始重试`);
178
- clearTimer(); i++;
179
- continue;
180
- }
181
- const poststat = await currObj.stat;
182
- switch(poststat){
183
- case "Completed"://完成
184
- SLogger.info(`第 ${currObj.index+1} 次 repeatPromise 成功`);
185
- //非当前
186
- if(currObj.index!=i)
187
- SLogger.info(`成功的 promise 非当前 promise 考虑增大重试间隔\n当前index: ${i}\n当前间隔: ${repeatTime}`);
188
- return currObj.result;
189
- case "Terminated"://终止
190
- SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 终止 停止重试`);
191
- return currObj.result;
192
- case "Failed"://验证失败
193
- //抛弃失败
194
- plist[currObj.index] = UtilFunc.getNeverResolvedPromise();
195
- //是当前
196
- if(currObj.index==i){
197
- SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 失败 开始重试`);
198
- clearTimer(); i++;
199
- continue;
200
- }
201
- //非当前
202
- SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 失败`);
203
- continue;
204
- }
205
- }
206
- //全部失败或超时则返回null
207
- SLogger.warn(`${repeatCount} 次 repeatPromise 尝试均失败`);
208
- return null;
209
- }catch(err){
210
- SLogger.warn(`repeatPromise 发生错误`,err);
211
- return null;
212
- }finally{
213
- //清理
214
- clearTimer();
215
- SLogger.timeEnd(timeflag);
216
- }
217
- }
218
-
219
-
220
- /**柯里化函数类型 */
221
- type CurryFunc<T, PrevArgs extends any[] = []> = T extends (...args: infer Args) => infer Result
222
- ? Args extends [infer Arg, ...infer RestArgs]
223
- ? RestArgs extends []
224
- ? ((...args: [...PrevArgs, Arg]) => Result )
225
- : ((...args: [...PrevArgs, Arg]) => CurryFunc<(...rest:RestArgs) => Result> )
226
- & (CurryFunc<(...args: RestArgs) => Result, [...PrevArgs, Arg]>)
227
- : Args extends []
228
- ? () => Result
229
- : never
230
- : never;
231
-
232
- /**柯里化转换
233
- * @param {T} fn - 将要转换的函数
234
- * @returns {CurryFunc<T>} 柯里化的函数
235
- */
236
- export function curry<T extends (...args: any[]) => any>(fn: T): CurryFunc<T> {
237
- return (function curried(...args: any[]) {
238
- if (args.length >= fn.length)
239
- return fn(...args);
240
- return (...restArgs: any[]) => curried(...args, ...restArgs);
241
- }) as CurryFunc<T>;
242
- }
243
- /**
244
- let sumvoid = ()=>10;
245
- let a = curry(sumvoid);//?
246
- console.log(a());
247
- let sum = (a:number,b:string,c:number,d:boolean)=>a+b+c+d;
248
- let sumCu = curry(sum);//?
249
- let suma = sumCu(1)("ss");//?
250
- let sumb = sumCu(1,"1")(2);//?
251
- let sumc = sumCu(4);//?
252
- let sumz = sumCu(1,"b",3)(false);//?
253
- console.log(suma(2,true));
254
- console.log(sumb(true));
255
- console.log(sumc("s",3,false));
256
- */
257
- /**可组合的函数 */
258
- type CompFunc<T = any, R = any> = (arg: T) => R;
259
- /**函数组合 从右到左执行 */
260
- export function compose<T>(...fs: CompFunc<T, T>[]): CompFunc<T, T>;
261
- export function compose<T, R>(f1: CompFunc<T, R>): CompFunc<T, R>;
262
- export function compose<T, R, R1>(f2: CompFunc<R, R1>, f1: CompFunc<T, R>): CompFunc<T, R1>;
263
- export function compose<T, R, R1, R2>(f3: CompFunc<R1, R2>, f2: CompFunc<R, R1>, f1: CompFunc<T, R>): CompFunc<T, R2>;
264
- export function compose<T, R, R1, R2, R3>(f4: CompFunc<R2, R3>, f3: CompFunc<R1, R2>, f2: CompFunc<R, R1>, f1: CompFunc<T, R>): CompFunc<T, R3>;
265
- export function compose<T, R, R1, R2, R3, R4>(f5: CompFunc<R3, R4>,f4: CompFunc<R2, R3>, f3: CompFunc<R1, R2>, f2: CompFunc<R, R1>, f1: CompFunc<T, R>): CompFunc<T, R4>;
266
- /**函数组合
267
- * 从右到左执行
268
- * @param {Function[]} funcs - 待组合的函数
269
- * @returns {(arg: any)=>any} 组合完成的函数
270
- */
271
- export function compose(...funcs: Function[]) {
272
- return (arg: any) => funcs.reduceRight((value, func) => func(value), arg);
273
- }
274
- /**函数管道 从左到右执行 */
275
- export function pipeline<T>(...fs: CompFunc<T, T>[]): CompFunc<T, T>;
276
- export function pipeline<T, R>(f1: CompFunc<T, R>): CompFunc<T, R>;
277
- export function pipeline<T, R, R1>(f1: CompFunc<T, R>, f2: CompFunc<R, R1>): CompFunc<T, R1>;
278
- export function pipeline<T, R, R1, R2>(f1: CompFunc<T, R>, f2: CompFunc<R, R1>, f3: CompFunc<R1, R2>): CompFunc<T, R2>;
279
- export function pipeline<T, R, R1, R2, R3>(f1: CompFunc<T, R>, f2: CompFunc<R, R1>, f3: CompFunc<R1, R2>, f4: CompFunc<R2, R3>): CompFunc<T, R3>;
280
- export function pipeline<T, R, R1, R2, R3, R4>(f1: CompFunc<T, R>, f2: CompFunc<R, R1>, f3: CompFunc<R1, R2>, f4: CompFunc<R2, R3>, f5: CompFunc<R3, R4>): CompFunc<T, R4>;
281
- /**函数管道
282
- * 从左到右执行
283
- * @param {((arg: T) => T)} funcs - 待组合的函数
284
- * @returns {((arg: T) => T)} 组合完成的函数
285
- */
286
- export function pipeline<T>(...funcs: ((arg: T) => T)[]): (arg: T) => T {
287
- return (arg: T): T => {
288
- return funcs.reduce((value, func) => func(value), arg);
289
- };
290
- }
291
-
292
- /**部分类组合
293
- * 将mixin的部分字段混入base
294
- * @param base - 基础类
295
- * @param mixin - 目标类
296
- * @param fields - 需要混入的字段
297
- * @returns - 混合完成的类
298
- */
299
- export function composePartClass<Base extends object,Mixin extends object>
300
- (base:Base,mixin:Mixin,...fields:(keyof Mixin)[]):ComposedPartClass<Base,Mixin,keyof Mixin>{
301
- const compObj = base as any;
302
- for(const fd of fields){
303
- Object.defineProperty(compObj, fd, {
304
- get: ()=>mixin[fd],
305
- set: (value)=>{mixin[fd] = value},
306
- enumerable:true ,
307
- //writable: true ,
308
- configurable: true
309
- });
310
- //(compObj as any)[fd] = (mixin[fd] as any).bind(mixin);
311
- }
312
- return compObj;
313
- }
314
- /**类组合
315
- * 将mixinList每个成员的字段混入base
316
- * @param base - 基础类
317
- * @param mixinList - 目标类
318
- * @returns - 混合完成的类
319
- */
320
- export function composeClass<Base extends object,MixinList extends object[]>
321
- (base:Base,...mixinList:MixinList):ComposedClassMult<Base,MixinList>{
322
- let obj = base as any;
323
- for(let mixin of mixinList as any){
324
- let propks = Object.getOwnPropertyNames(mixin.constructor.prototype)
325
- for(const key of propks){
326
- if(key != "constructor"){
327
- Object.defineProperty(obj, key, {
328
- get: ()=>mixin[key],
329
- set: (value)=>{mixin[key] = value},
330
- enumerable:true,
331
- //writable: true,
332
- configurable: true
333
- });
334
- //obj[key] = (mixin as any)[key];
335
- }
336
- }
337
- for(const key in mixin){
338
- Object.defineProperty(obj, key, {
339
- get: ()=>mixin[key],
340
- set: (value)=>{mixin[key] = value},
341
- enumerable:true ,
342
- //writable: true ,
343
- configurable: true
344
- });
345
- //obj[key] = (mixin as any)[key];
346
- }
347
- }
348
- return obj;
349
- }
350
-
351
- /**对对象的每个属性应用映射函数,并返回一个新的对象。
352
- * @template T - 对象的类型
353
- * @param obj - 要处理的对象
354
- * @param mapper - 映射函数,接受一个值和一个键,返回一个新的值
355
- * @returns - 一个新的对象,它的属性是原对象的属性经过映射函数处理后的结果
356
- */
357
- export function mapObject<T extends Object>
358
- (obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T {
359
- return Object.entries(obj).reduce((result, [key, value]) => {
360
- result[key as keyof T] = mapper(key as keyof T, value);
361
- return result;
362
- }, {} as T);
363
- }
364
-
1
+ import * as crypto from "crypto";
2
+ import { ComposedClass, ComposedClassMult, ComposedClassPart, FuncPropNames, JToken, PromiseProcFn, PromiseStat, PromiseVerifyFn } from "@src/UtilInterfaces";
3
+ import * as cp from "child_process";
4
+ import { SLogger } from "@src/UtilLogger";
5
+
6
+ /**常用函数 */
7
+ export namespace UtilFunc{
8
+ /**获取当前时间戳
9
+ * @returns 时间戳
10
+ */
11
+ export function getTime(): number {
12
+ return new Date().getTime();
13
+ }
14
+
15
+ /**初始化对象的字段
16
+ * 会改变obj
17
+ * @param obj - 所要初始化的对象
18
+ * @param field - 所要初始化的字段
19
+ * @param defaultVal - 默认值
20
+ * @returns 最终值
21
+ */
22
+ export function initField<T>(
23
+ obj: Record<string, T>,
24
+ field: string,
25
+ defaultVal: T
26
+ ): T {
27
+ if (!(field in obj)) obj[field] = defaultVal;
28
+ return obj[field];
29
+ }
30
+
31
+ /**生成一串uuid
32
+ * @returns uuid
33
+ */
34
+ export function genUUID() {
35
+ return crypto.randomBytes(16).toString("hex");
36
+ }
37
+ /**计算Hash
38
+ * @param str - 待计算的字符串
39
+ * @returns hash
40
+ */
41
+ export function calcHash(str:string) {
42
+ return crypto.createHash('md5').update(str).digest('hex');
43
+ }
44
+
45
+ /**深克隆 序列化并反序列化
46
+ * @template T - JToken类型的泛型
47
+ * @param obj - 克隆目标
48
+ * @returns 克隆结果
49
+ */
50
+ export function deepClone<T extends JToken>(obj: T): T {
51
+ return JSON.parse(JSON.stringify(obj));
52
+ }
53
+
54
+ /**是否为安全的数字
55
+ * @param num - 所要检测的数字
56
+ * @returns 是否安全
57
+ */
58
+ export function isSafeNumber(num: number): boolean {
59
+ if (num === undefined || num == null || isNaN(num)) return false;
60
+ if(typeof num === 'number') return true;
61
+ return false;
62
+ }
63
+
64
+ /**等待 timeMs 毫秒
65
+ * @async
66
+ * @param timeMs - 等待的毫秒数
67
+ * @returns
68
+ */
69
+ export async function sleep(timeMs: number): Promise<boolean> {
70
+ return new Promise(function (resolve, rejecte) {
71
+ let timer = setTimeout(function () {
72
+ resolve(true);
73
+ }, timeMs);
74
+ });
75
+ }
76
+
77
+ /**封装的 cp.exec 执行一段指令 指令完成后返回 Promise
78
+ * @param command 指令文本
79
+ */
80
+ export function exec(command: string) {
81
+ return new Promise<{ stdout:string, stderr:string }>
82
+ ((resolve, reject) => {
83
+ cp.exec(command, (error, stdout, stderr) => {
84
+ if (error)
85
+ reject(error);
86
+ else
87
+ resolve({ stdout, stderr });
88
+ });
89
+ });
90
+ }
91
+
92
+ /**永不完成的Promise单例 */
93
+ const NeverResolvedPromise = new Promise(()=>{});
94
+ /**获得一个永不完成的Promise单例 */
95
+ export function getNeverResolvedPromise<T>():Promise<T>{
96
+ return NeverResolvedPromise as Promise<T>;
97
+ }
98
+
99
+ /**进行中的请求 */
100
+ type ProcessingPromise<T> = {
101
+ /**主体请求 */
102
+ result:T;
103
+ /**请求状态 */
104
+ stat:PromiseStat|Promise<PromiseStat>;
105
+ /**请求下标/序号 */
106
+ index:number;
107
+ };
108
+
109
+ /**重复尝试promise
110
+ * @async
111
+ * @param procFn - 发起函数
112
+ * @param verifyFn - 验证函数
113
+ * @param repeatCount - 重试次数
114
+ * @param repeatTime - 超时时间/秒 最小为10秒
115
+ * @returns - 结果 null 为全部失败/超时
116
+ */
117
+ export async function repeatPromise<T>(procFn:PromiseProcFn<T>,verifyFn?:PromiseVerifyFn<T>,
118
+ repeatCount:number=3,repeatTime:number=180):Promise<T|null>{
119
+
120
+ //计时
121
+ const timeflag = "repeatPromise "+UtilFunc.genUUID();
122
+ SLogger.time(timeflag);
123
+
124
+ //转换为毫秒
125
+ const hasRepeatTime = (repeatTime>=10);
126
+ if(hasRepeatTime) repeatTime*=1000;
127
+
128
+ //验证处理函数
129
+ if(verifyFn===undefined)
130
+ verifyFn = ()=>"Completed";
131
+
132
+ //计时器
133
+ let timer:NodeJS.Timer|null = null;
134
+ let timerP:Promise<"Timeout">|null=null;
135
+ let resolveFn:((value: "Timeout" | PromiseLike<"Timeout">)=>void)|null = null;
136
+ /**清理计时器 */
137
+ const clearTimer = ()=>{
138
+ if(timer!=null)
139
+ clearInterval(timer);
140
+ if(resolveFn!=null)
141
+ resolveFn("Timeout");
142
+ timerP=null;
143
+ timer=null;
144
+ resolveFn=null;
145
+ }
146
+
147
+ //进行中的请求
148
+ const plist:Promise<ProcessingPromise<T>>[] = [];
149
+
150
+ //开始处理
151
+ try{
152
+ for(let i=0;i<repeatCount;){
153
+ SLogger.info(`开始第 ${i+1} 次 repeatPromise`);
154
+ //创建当前任务
155
+ if(plist.length<i+1){
156
+ plist.push(procFn().then(result =>
157
+ ({result, stat:verifyFn!(result), index:i})));
158
+ }
159
+
160
+ //创建定时器
161
+ if(timerP==null){
162
+ timerP = new Promise<"Timeout">(function(resolve, rejecte){
163
+ resolveFn = resolve;
164
+ timer = setTimeout(()=>resolve("Timeout"),
165
+ hasRepeatTime? repeatTime:Infinity);//无限制则无限时间
166
+ })
167
+ }
168
+
169
+ //等待完成
170
+ const currObj = await Promise.race([...plist, timerP]);
171
+
172
+ //超时处理
173
+ if(currObj=="Timeout"){
174
+ SLogger.warn(`第 ${i+1} 次 repeatPromise 超时 ${repeatTime} ms 开始重试`);
175
+ clearTimer(); i++;
176
+ continue;
177
+ }
178
+ const poststat = await currObj.stat;
179
+ switch(poststat){
180
+ case "Completed"://完成
181
+ SLogger.info(`第 ${currObj.index+1} repeatPromise 成功`);
182
+ //非当前
183
+ if(currObj.index!=i)
184
+ SLogger.info(`成功的 promise 非当前 promise 考虑增大重试间隔\n当前index: ${i}\n当前间隔: ${repeatTime}`);
185
+ return currObj.result;
186
+ case "Terminated"://终止
187
+ SLogger.warn(`第 ${currObj.index+1} repeatPromise 终止 停止重试`);
188
+ return currObj.result;
189
+ case "Failed"://验证失败
190
+ //抛弃失败
191
+ plist[currObj.index] = UtilFunc.getNeverResolvedPromise();
192
+ //是当前
193
+ if(currObj.index==i){
194
+ SLogger.warn(`第 ${currObj.index+1} repeatPromise 失败 开始重试`);
195
+ clearTimer(); i++;
196
+ continue;
197
+ }
198
+ //非当前
199
+ SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 失败`);
200
+ continue;
201
+ }
202
+ }
203
+ //全部失败或超时则返回null
204
+ SLogger.warn(`${repeatCount} 次 repeatPromise 尝试均失败`);
205
+ return null;
206
+ }catch(err){
207
+ SLogger.warn(`repeatPromise 发生错误`,err);
208
+ return null;
209
+ }finally{
210
+ //清理
211
+ clearTimer();
212
+ SLogger.timeEnd(timeflag);
213
+ }
214
+ }
215
+
216
+ /**部分类组合
217
+ * 将mixin的部分字段混入base
218
+ * @param base - 基础类
219
+ * @param mixin - 目标类
220
+ * @param fields - 需要混入的字段
221
+ * @returns 混合完成的类
222
+ */
223
+ export function composeClassPart
224
+ <Base extends object,Mixin extends object,Field extends keyof Mixin>
225
+ (base:Base,mixin:Mixin,...fields:Field[]):ComposedClassPart<Base,Mixin,Field>{
226
+ const compObj = base as any;
227
+ for(const fd of fields){
228
+ Object.defineProperty(compObj, fd, {
229
+ get: ()=>mixin[fd],
230
+ set: (value)=>{mixin[fd] = value},
231
+ enumerable:true ,
232
+ //writable: true ,
233
+ configurable: true
234
+ });
235
+ //(compObj as any)[fd] = (mixin[fd] as any).bind(mixin);
236
+ }
237
+ return compObj;
238
+ }
239
+ /**类组合
240
+ * 将mixinList每个成员的字段混入base
241
+ * @param base - 基础类
242
+ * @param mixinList - 目标类
243
+ * @returns - 混合完成的类
244
+ */
245
+ export function composeClass<Base extends object,MixinList extends object[]>
246
+ (base:Base,...mixinList:MixinList):ComposedClassMult<Base,MixinList>{
247
+ let obj = base as any;
248
+ for(let mixin of mixinList as any){
249
+ let propks = Object.getOwnPropertyNames(mixin.constructor.prototype)
250
+ for(const key of propks){
251
+ if(key != "constructor"){
252
+ Object.defineProperty(obj, key, {
253
+ get: ()=>mixin[key],
254
+ set: (value)=>{mixin[key] = value},
255
+ enumerable:true,
256
+ //writable: true,
257
+ configurable: true
258
+ });
259
+ //obj[key] = (mixin as any)[key];
260
+ }
261
+ }
262
+ for(const key in mixin){
263
+ Object.defineProperty(obj, key, {
264
+ get: ()=>mixin[key],
265
+ set: (value)=>{mixin[key] = value},
266
+ enumerable:true ,
267
+ //writable: true ,
268
+ configurable: true
269
+ });
270
+ //obj[key] = (mixin as any)[key];
271
+ }
272
+ }
273
+ return obj;
274
+ }
275
+
276
+ /**对对象的每个属性应用映射函数,并返回一个新的对象。
277
+ * @template T - 对象的类型
278
+ * @param obj - 要处理的对象
279
+ * @param mapper - 映射函数,接受一个值和一个键,返回一个新的值
280
+ * @returns - 一个新的对象,它的属性是原对象的属性经过映射函数处理后的结果
281
+ */
282
+ export function mapEntries<T extends Object>
283
+ (obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T {
284
+ return Object.entries(obj).reduce((result, [key, value]) => {
285
+ result[key as keyof T] = mapper(key as keyof T, value);
286
+ return result;
287
+ }, {} as T);
288
+ }
289
+
365
290
  }