@zwa73/utils 1.0.77 → 1.0.78

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,15 @@
1
+ import { ExtractOutcome, Keyable, Outcome } from "./UtilInterfaces";
2
+ /**创建一个outcome */
3
+ export declare function outcome<K extends Keyable, V>(key: K, value: V): Outcome<K, V>;
4
+ /**处理联合 简单值
5
+ * @param t - 目标值
6
+ * @param procObj - 所有可能的id组成的处理函数映射
7
+ * @returns 任意处理函数的返回值
8
+ */
9
+ export declare function match<T extends Keyable | Outcome<Keyable, unknown>, P extends (T extends Keyable ? {
10
+ [K in T]: (k: K) => unknown;
11
+ } : T extends Outcome<Keyable, unknown> ? {
12
+ [K in T['status']]: (k: K, v: ExtractOutcome<T, K>['result']) => unknown;
13
+ } : never)>(t: T, procObj: P): P extends Record<any, (...args: any) => any> ? {
14
+ [K in keyof P]: ReturnType<P[K]>;
15
+ }[keyof P] : never;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.match = exports.outcome = void 0;
4
+ /**创建一个outcome */
5
+ function outcome(key, value) {
6
+ return { status: key, result: value };
7
+ }
8
+ exports.outcome = outcome;
9
+ /**处理联合 简单值
10
+ * @param t - 目标值
11
+ * @param procObj - 所有可能的id组成的处理函数映射
12
+ * @returns 任意处理函数的返回值
13
+ */
14
+ function match(t, procObj) {
15
+ if (typeof t === 'string' || typeof t === 'number' || typeof t === 'symbol')
16
+ return procObj[t](t);
17
+ else
18
+ return procObj[t.status](t.status, t.result);
19
+ }
20
+ exports.match = match;
21
+ if (false) {
22
+ let a = null;
23
+ const r = match(a, {
24
+ "asd": (a) => "ssa",
25
+ "dsa": (b) => "ssb",
26
+ });
27
+ }
@@ -1,5 +1,15 @@
1
1
  type TDTg<T> = (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T>;
2
2
  type DTg = (target: Object, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
3
+ /**用于打印方法运行时间
4
+ * @param flag - 时间标签
5
+ * @param suffixUID - 是否尾随uid
6
+ */
7
+ export declare function LogTime(flag: string, suffixUID?: boolean): DTg;
8
+ /**用于打印异步方法运行时间
9
+ * @param flag - 时间标签
10
+ * @param suffixUID - 是否尾随uid
11
+ */
12
+ export declare function LogTimeAsync(flag: string, suffixUID?: boolean): DTg;
3
13
  /**用于打印方法的调用 */
4
14
  export declare function LogCall(): DTg;
5
15
  /**用于打印异步方法的调用 */
@@ -9,8 +9,45 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.CatchAsync = exports.DCatch = exports.DeferAsync = exports.Defer = exports.LogErrAsync = exports.LogErr = exports.LogCallAsync = exports.LogCall = void 0;
12
+ exports.CatchAsync = exports.DCatch = exports.DeferAsync = exports.Defer = exports.LogErrAsync = exports.LogErr = exports.LogCallAsync = exports.LogCall = exports.LogTimeAsync = exports.LogTime = void 0;
13
+ const UtilFunctions_1 = require("./UtilFunctions");
13
14
  const UtilLogger_1 = require("./UtilLogger");
15
+ /**用于打印方法运行时间
16
+ * @param flag - 时间标签
17
+ * @param suffixUID - 是否尾随uid
18
+ */
19
+ function LogTime(flag, suffixUID) {
20
+ return function (target, propertyKey, descriptor) {
21
+ const originalMethod = descriptor.value;
22
+ descriptor.value = function (...args) {
23
+ const uid = suffixUID ? UtilFunctions_1.UtilFunc.genUUID() : "";
24
+ UtilLogger_1.SLogger.time(flag + uid);
25
+ let result = originalMethod.apply(this, args);
26
+ UtilLogger_1.SLogger.timeEnd(flag + uid);
27
+ return result;
28
+ };
29
+ return descriptor;
30
+ };
31
+ }
32
+ exports.LogTime = LogTime;
33
+ /**用于打印异步方法运行时间
34
+ * @param flag - 时间标签
35
+ * @param suffixUID - 是否尾随uid
36
+ */
37
+ function LogTimeAsync(flag, suffixUID) {
38
+ return function (target, propertyKey, descriptor) {
39
+ const originalMethod = descriptor.value;
40
+ descriptor.value = async function (...args) {
41
+ const uid = suffixUID ? UtilFunctions_1.UtilFunc.genUUID() : "";
42
+ UtilLogger_1.SLogger.time(flag + uid);
43
+ let result = await originalMethod.apply(this, args);
44
+ UtilLogger_1.SLogger.timeEnd(flag + uid);
45
+ return result;
46
+ };
47
+ return descriptor;
48
+ };
49
+ }
50
+ exports.LogTimeAsync = LogTimeAsync;
14
51
  /**用于打印方法的调用 */
15
52
  function LogCall() {
16
53
  return function (target, propertyKey, descriptor) {
@@ -158,7 +195,7 @@ class Example {
158
195
  myMethod(num) {
159
196
  return num;
160
197
  }
161
- async myMethod1(num, ss) {
198
+ static async myMethod1(num, ss) {
162
199
  return 312;
163
200
  }
164
201
  }
@@ -174,7 +211,7 @@ __decorate([
174
211
  __metadata("design:type", Function),
175
212
  __metadata("design:paramtypes", [Number, String]),
176
213
  __metadata("design:returntype", Promise)
177
- ], Example.prototype, "myMethod1", null);
214
+ ], Example, "myMethod1", null);
178
215
  //let e = new Example();
179
216
  //e.myMethod1(1,"");
180
217
  //console.log(123);
@@ -1,10 +1,13 @@
1
- import { ComposedClass, ComposedMixinable, ExtractOutcome, IJData, JObject, JToken, Mixinable, Outcome, PromiseVerifyFn } from "./UtilInterfaces";
1
+ import { ComposedClass, ComposedMixinable, IJData, JObject, JToken, Mixinable, Outcome, PromiseVerifyFn } from "./UtilInterfaces";
2
+ import { Completed, Timeout } from "./UtilSymbol";
3
+ type CompleteCome<T> = Outcome<Completed, T>;
4
+ type TimeoutCome<T> = Outcome<Timeout, Promise<T>>;
2
5
  /**常用函数 */
3
- export declare namespace UtilFunc {
6
+ export declare class UtilFunc {
4
7
  /**获取当前时间戳
5
8
  * @returns 时间戳
6
9
  */
7
- function getTime(): number;
10
+ static getTime(): number;
8
11
  /**初始化对象的字段
9
12
  * 会改变obj
10
13
  * @param obj - 所要初始化的对象
@@ -12,50 +15,57 @@ export declare namespace UtilFunc {
12
15
  * @param defaultVal - 默认值
13
16
  * @returns 最终值
14
17
  */
15
- function initField<T extends object, K extends keyof T>(obj: T, field: K, defaultVal: T[K]): T[K];
18
+ static initField<T extends object, K extends keyof T>(obj: T, field: K, defaultVal: T[K]): T[K];
16
19
  /**初始化一个数据对象
17
20
  * @param obj - 目标对象
18
21
  * @param checkObj - 用于检测的对象 在对应key缺失时赋予对应值 如果值为函数, 则赋予执行结果 如果结果为 undefined 则不赋值
19
22
  * @returns 完成初始化的对象
20
23
  */
21
- function initObject<T extends JObject>(obj: T, checkObj: {
24
+ static initObject<T extends JObject>(obj: T, checkObj: {
22
25
  [P in keyof T]: T[P] | (() => void | T[P]);
23
26
  }): any;
24
27
  /**生成一串uuid
25
28
  * @returns uuid
26
29
  */
27
- function genUUID(): string;
30
+ static genUUID(): string;
28
31
  /**计算Hash
29
32
  * @param str - 待计算的字符串
30
33
  * @returns hash
31
34
  */
32
- function calcHash(str: string): string;
35
+ static calcHash(str: string): string;
33
36
  /**深克隆 序列化并反序列化
34
37
  * @template T - JToken类型的泛型
35
38
  * @param obj - 克隆目标
36
39
  * @returns 克隆结果
37
40
  */
38
- function deepClone<T extends JToken>(obj: T): T;
41
+ static deepClone<T extends JToken>(obj: T): T;
39
42
  /**是否为安全的数字
40
43
  * @param num - 所要检测的数字
41
44
  * @returns 是否安全
42
45
  */
43
- function isSafeNumber(num: number): boolean;
46
+ static isSafeNumber(num: number): boolean;
44
47
  /**等待 timeMs 毫秒
45
48
  * @async
46
49
  * @param timeMs - 等待的毫秒数
47
50
  * @returns
48
51
  */
49
- function sleep(timeMs: number): Promise<boolean>;
52
+ static sleep<T>(timeMs: number): Promise<void>;
53
+ /**等待 timeMs 毫秒
54
+ * @async
55
+ * @param timeMs - 等待的毫秒数
56
+ * @param result - 结果
57
+ * @returns
58
+ */
59
+ static sleep<T>(timeMs: number, result: T): Promise<T>;
50
60
  /**封装的 cp.exec 执行一段指令 指令完成后返回 Promise
51
61
  * @param command 指令文本
52
62
  */
53
- function exec(command: string): Promise<{
63
+ static exec(command: string): Promise<{
54
64
  stdout: string;
55
65
  stderr: string;
56
66
  }>;
57
67
  /**获得一个永不完成的Promise单例 */
58
- function getNeverResolvedPromise<T>(): Promise<T>;
68
+ static getNeverResolvedPromise<T>(): Promise<T>;
59
69
  /**重复尝试promise
60
70
  * @async
61
71
  * @param procFn - 发起函数
@@ -64,7 +74,13 @@ export declare namespace UtilFunc {
64
74
  * @param repeatTime - 超时时间/秒 最小为10秒
65
75
  * @returns 结果 null 为全部失败/超时
66
76
  */
67
- function repeatPromise<T>(procFn: () => Promise<T>, verifyFn?: PromiseVerifyFn<T>, repeatCount?: number, repeatTime?: number): Promise<T | null>;
77
+ static repeatPromise<T>(procFn: () => Promise<T>, verifyFn?: PromiseVerifyFn<T>, repeatCount?: number, repeatTime?: number): Promise<T | null>;
78
+ /**创建一个限时的Promise
79
+ * @param func - 处理函数
80
+ * @param timeLimit - 毫秒限时
81
+ * @returns 超时则返回 处理函数委托 完成则返回结果
82
+ */
83
+ static timelimitPromise<T>(func: () => Promise<T> | T, timeLimit?: number): Promise<CompleteCome<T> | TimeoutCome<T>>;
68
84
  /**部分类组合
69
85
  * 将mixin的部分字段混入base
70
86
  * @param base - 基础类
@@ -73,40 +89,21 @@ export declare namespace UtilFunc {
73
89
  * @param fields - 需要混入的字段
74
90
  * @returns 混合完成的类
75
91
  */
76
- function composeClassPart<Base extends object, Mixin extends object, Field extends keyof Mixin>(base: Base, mixin: Mixin, key: string, ...fields: Field[]): ComposedClass<Base, Mixin, typeof key, Field>;
92
+ static composeClassPart<Base extends object, Mixin extends object, Field extends keyof Mixin>(base: Base, mixin: Mixin, key: string, ...fields: Field[]): ComposedClass<Base, Mixin, typeof key, Field>;
77
93
  /**根据 MIXIN_FIELDS 自动混入 */
78
- function composeMixinable<Base extends object, Mixins extends Mixinable<any>[]>(base: Base, ...mixins: Mixins): ComposedMixinable<Base, Mixins>;
94
+ static composeMixinable<Base extends object, Mixins extends Mixinable<any>[]>(base: Base, ...mixins: Mixins): ComposedMixinable<Base, Mixins>;
79
95
  /**对对象的每个属性应用映射函数,并返回一个新的对象。
80
96
  * @template T - 对象的类型
81
97
  * @param obj - 要处理的对象
82
98
  * @param mapper - 映射函数,接受一个值和一个键,返回一个新的值
83
99
  * @returns - 一个新的对象,它的属性是原对象的属性经过映射函数处理后的结果
84
100
  */
85
- function mapEntries<T extends Object>(obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T;
86
- /**处理联合 Outcome
87
- * @param t - 目标值
88
- * @param procObj - 所有可能的id组成的处理函数映射
89
- * @returns 任意处理函数的返回值
90
- */
91
- function matchOutcome<T extends Outcome<string, unknown>, P extends {
92
- [K in T['status']]: (k: K, v: ExtractOutcome<T, K>['result']) => unknown;
93
- }>(t: T, procObj: P): {
94
- [K in keyof P]: ReturnType<P[K]>;
95
- }[keyof P];
96
- /**处理联合 字符串
97
- * @param t - 目标值
98
- * @param procObj - 所有可能的id组成的处理函数映射
99
- * @returns 任意处理函数的返回值
100
- */
101
- function matchStr<T extends string, P extends {
102
- [K in T]: (k: K) => unknown;
103
- }>(t: T, procObj: P): {
104
- [K in keyof P]: ReturnType<P[K]>;
105
- }[keyof P];
101
+ static mapEntries<T extends Object>(obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T;
106
102
  /**将JToken转换为字符串
107
103
  * @param token - 待转换的Token
108
104
  * @param space - 插入的空格 数字为空格数量 默认为制表符\t
109
105
  * @returns 转换完成的字符串
110
106
  */
111
- function stringifyJToken(token: JToken | IJData, space?: string | number | null | undefined): string;
107
+ static stringifyJToken(token: JToken | IJData, space?: string | number | null | undefined): string;
112
108
  }
109
+ export {};
@@ -1,19 +1,31 @@
1
1
  "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.UtilFunc = void 0;
4
13
  const crypto = require("crypto");
5
14
  const cp = require("child_process");
6
15
  const UtilLogger_1 = require("./UtilLogger");
16
+ const UtilSymbol_1 = require("./UtilSymbol");
17
+ const QuickFunction_1 = require("./QuickFunction");
18
+ const UtilDecorators_1 = require("./UtilDecorators");
19
+ /**永不完成的Promise单例 */
20
+ const NeverResolvedPromise = new Promise(() => { });
7
21
  /**常用函数 */
8
- var UtilFunc;
9
- (function (UtilFunc) {
22
+ class UtilFunc {
10
23
  /**获取当前时间戳
11
24
  * @returns 时间戳
12
25
  */
13
- function getTime() {
26
+ static getTime() {
14
27
  return new Date().getTime();
15
28
  }
16
- UtilFunc.getTime = getTime;
17
29
  /**初始化对象的字段
18
30
  * 会改变obj
19
31
  * @param obj - 所要初始化的对象
@@ -21,18 +33,17 @@ var UtilFunc;
21
33
  * @param defaultVal - 默认值
22
34
  * @returns 最终值
23
35
  */
24
- function initField(obj, field, defaultVal) {
36
+ static initField(obj, field, defaultVal) {
25
37
  if (!(field in obj))
26
38
  obj[field] = defaultVal;
27
39
  return obj[field];
28
40
  }
29
- UtilFunc.initField = initField;
30
41
  /**初始化一个数据对象
31
42
  * @param obj - 目标对象
32
43
  * @param checkObj - 用于检测的对象 在对应key缺失时赋予对应值 如果值为函数, 则赋予执行结果 如果结果为 undefined 则不赋值
33
44
  * @returns 完成初始化的对象
34
45
  */
35
- function initObject(obj, checkObj) {
46
+ static initObject(obj, checkObj) {
36
47
  const fixobj = obj;
37
48
  for (const key in checkObj) {
38
49
  if (obj[key] !== undefined)
@@ -48,60 +59,49 @@ var UtilFunc;
48
59
  }
49
60
  return fixobj;
50
61
  }
51
- UtilFunc.initObject = initObject;
52
62
  /**生成一串uuid
53
63
  * @returns uuid
54
64
  */
55
- function genUUID() {
65
+ static genUUID() {
56
66
  return crypto.randomBytes(16).toString("hex");
57
67
  }
58
- UtilFunc.genUUID = genUUID;
59
68
  /**计算Hash
60
69
  * @param str - 待计算的字符串
61
70
  * @returns hash
62
71
  */
63
- function calcHash(str) {
72
+ static calcHash(str) {
64
73
  return crypto.createHash('md5').update(str).digest('hex');
65
74
  }
66
- UtilFunc.calcHash = calcHash;
67
75
  /**深克隆 序列化并反序列化
68
76
  * @template T - JToken类型的泛型
69
77
  * @param obj - 克隆目标
70
78
  * @returns 克隆结果
71
79
  */
72
- function deepClone(obj) {
80
+ static deepClone(obj) {
73
81
  return JSON.parse(JSON.stringify(obj));
74
82
  }
75
- UtilFunc.deepClone = deepClone;
76
83
  /**是否为安全的数字
77
84
  * @param num - 所要检测的数字
78
85
  * @returns 是否安全
79
86
  */
80
- function isSafeNumber(num) {
87
+ static isSafeNumber(num) {
81
88
  if (num === undefined || num == null || isNaN(num))
82
89
  return false;
83
90
  if (typeof num === 'number')
84
91
  return true;
85
92
  return false;
86
93
  }
87
- UtilFunc.isSafeNumber = isSafeNumber;
88
- /**等待 timeMs 毫秒
89
- * @async
90
- * @param timeMs - 等待的毫秒数
91
- * @returns
92
- */
93
- async function sleep(timeMs) {
94
+ static async sleep(timeMs, result) {
94
95
  return new Promise(function (resolve, rejecte) {
95
96
  let timer = setTimeout(function () {
96
- resolve(true);
97
+ resolve(result);
97
98
  }, timeMs);
98
99
  });
99
100
  }
100
- UtilFunc.sleep = sleep;
101
101
  /**封装的 cp.exec 执行一段指令 指令完成后返回 Promise
102
102
  * @param command 指令文本
103
103
  */
104
- function exec(command) {
104
+ static exec(command) {
105
105
  return new Promise((resolve, reject) => {
106
106
  cp.exec(command, (error, stdout, stderr) => {
107
107
  if (error)
@@ -111,14 +111,10 @@ var UtilFunc;
111
111
  });
112
112
  });
113
113
  }
114
- UtilFunc.exec = exec;
115
- /**永不完成的Promise单例 */
116
- const NeverResolvedPromise = new Promise(() => { });
117
114
  /**获得一个永不完成的Promise单例 */
118
- function getNeverResolvedPromise() {
115
+ static getNeverResolvedPromise() {
119
116
  return NeverResolvedPromise;
120
117
  }
121
- UtilFunc.getNeverResolvedPromise = getNeverResolvedPromise;
122
118
  /**重复尝试promise
123
119
  * @async
124
120
  * @param procFn - 发起函数
@@ -127,10 +123,7 @@ var UtilFunc;
127
123
  * @param repeatTime - 超时时间/秒 最小为10秒
128
124
  * @returns 结果 null 为全部失败/超时
129
125
  */
130
- async function repeatPromise(procFn, verifyFn, repeatCount = 3, repeatTime = 180) {
131
- //计时
132
- const timeflag = "repeatPromise " + UtilFunc.genUUID();
133
- UtilLogger_1.SLogger.time(timeflag);
126
+ static async repeatPromise(procFn, verifyFn, repeatCount = 3, repeatTime = 180) {
134
127
  /**是否含有超时时间 */
135
128
  const hasRepeatTime = (repeatTime >= 10);
136
129
  //转换为毫秒
@@ -138,21 +131,7 @@ var UtilFunc;
138
131
  repeatTime *= 1000;
139
132
  //验证处理函数
140
133
  if (verifyFn === undefined)
141
- verifyFn = () => "Completed";
142
- /**计时器 */
143
- let timer = null;
144
- /**计时器 Promise */
145
- let timerP = null;
146
- /**计时器 Promise 的返回函数 */
147
- let resolveFn = null;
148
- /**清理计时器 */
149
- const clearTimer = () => {
150
- if (timer)
151
- clearInterval(timer);
152
- if (resolveFn)
153
- resolveFn("Timeout");
154
- timerP = timer = resolveFn = null;
155
- };
134
+ verifyFn = () => UtilSymbol_1.Completed;
156
135
  //进行中的请求
157
136
  const plist = [];
158
137
  //开始处理
@@ -162,53 +141,54 @@ var UtilFunc;
162
141
  UtilLogger_1.SLogger.info(`开始第 ${i + 1} 次 repeatPromise`);
163
142
  //如果 plist 中当前下标的任务还未创建 则 创建当前任务
164
143
  if (plist.length < i + 1) {
165
- plist.push(procFn().then(result => ({ result, stat: verifyFn(result), index: i })));
166
- }
167
- //创建定时器
168
- if (timerP == null) {
169
- timerP = new Promise((resolve, rejecte) => {
170
- resolveFn = resolve;
171
- timer = setTimeout(() => resolve("Timeout"), hasRepeatTime ? repeatTime : Infinity); //无限制则无限时间
172
- });
144
+ plist.push(UtilFunc.timelimitPromise(async () => {
145
+ const result = await procFn();
146
+ const stat = await verifyFn(result);
147
+ return { result, stat, index: i };
148
+ }));
173
149
  }
174
150
  //等待任意任务 或当前计时器完成
175
- const currObj = await Promise.race([...plist, timerP]);
151
+ const currObj = await Promise.race([...plist]);
176
152
  //超时处理
177
- if (currObj === "Timeout") {
153
+ if (currObj.status === UtilSymbol_1.Timeout) {
154
+ //解除timeout替换原参数
155
+ plist[i] = new Promise(async (rslove) => {
156
+ const res = await currObj.result;
157
+ rslove((0, QuickFunction_1.outcome)(UtilSymbol_1.Completed, res));
158
+ });
178
159
  UtilLogger_1.SLogger.warn(`第 ${i + 1} 次 repeatPromise 超时 ${repeatTime} ms 开始重试`);
179
- clearTimer();
180
160
  i++;
181
161
  continue;
182
162
  }
183
163
  //路由请求状态
184
- const poststat = await currObj.stat;
185
- const result = matchStr(poststat, {
186
- Completed() {
187
- UtilLogger_1.SLogger.info(`第 ${currObj.index + 1} 次 repeatPromise 成功`);
164
+ const postresult = currObj.result;
165
+ const result = (0, QuickFunction_1.match)(postresult.stat, {
166
+ [UtilSymbol_1.Completed]() {
167
+ UtilLogger_1.SLogger.info(`第 ${postresult.index + 1} 次 repeatPromise 成功`);
188
168
  //非当前
189
- if (currObj.index != i)
169
+ if (postresult.index != i)
190
170
  UtilLogger_1.SLogger.info(`成功的 promise 非当前 promise 考虑增大重试间隔\n当前index: ${i}\n当前间隔: ${repeatTime}`);
191
- return currObj.result;
171
+ return postresult.result;
192
172
  },
193
- Terminated() {
194
- UtilLogger_1.SLogger.warn(`第 ${currObj.index + 1} 次 repeatPromise 终止 停止重试`);
195
- return currObj.result;
173
+ [UtilSymbol_1.Terminated]() {
174
+ UtilLogger_1.SLogger.warn(`第 ${postresult.index + 1} 次 repeatPromise 终止 停止重试`);
175
+ return postresult.result;
196
176
  },
197
- Failed() {
177
+ [UtilSymbol_1.Failed]() {
198
178
  //抛弃失败
199
- plist[currObj.index] = UtilFunc.getNeverResolvedPromise();
179
+ plist[postresult.index] = UtilFunc.getNeverResolvedPromise();
200
180
  //是当前
201
- if (currObj.index == i) {
202
- UtilLogger_1.SLogger.warn(`第 ${currObj.index + 1} 次 repeatPromise 失败 开始重试`);
203
- clearTimer();
181
+ if (postresult.index == i) {
182
+ UtilLogger_1.SLogger.warn(`第 ${postresult.index + 1} 次 repeatPromise 失败 开始重试`);
204
183
  i++;
205
- return;
184
+ return UtilSymbol_1.None;
206
185
  }
207
186
  //非当前
208
- UtilLogger_1.SLogger.warn(`第 ${currObj.index + 1} 次 repeatPromise 失败`);
187
+ UtilLogger_1.SLogger.warn(`第 ${postresult.index + 1} 次 repeatPromise 失败`);
188
+ return UtilSymbol_1.None;
209
189
  },
210
190
  });
211
- if (result !== undefined)
191
+ if (result !== UtilSymbol_1.None)
212
192
  return result;
213
193
  }
214
194
  //全部失败或超时则返回null
@@ -219,13 +199,35 @@ var UtilFunc;
219
199
  UtilLogger_1.SLogger.warn(`repeatPromise 发生错误`, err);
220
200
  return null;
221
201
  }
222
- finally {
223
- //清理
224
- clearTimer();
225
- UtilLogger_1.SLogger.timeEnd(timeflag);
226
- }
227
202
  }
228
- UtilFunc.repeatPromise = repeatPromise;
203
+ /**创建一个限时的Promise
204
+ * @param func - 处理函数
205
+ * @param timeLimit - 毫秒限时
206
+ * @returns 超时则返回 处理函数委托 完成则返回结果
207
+ */
208
+ static timelimitPromise(func, timeLimit) {
209
+ return new Promise((reslove) => {
210
+ let clearTimer = null;
211
+ let proc = (async () => await func())();
212
+ const procerP = new Promise(async (resolve) => {
213
+ const res = await proc;
214
+ if (clearTimer)
215
+ clearTimer();
216
+ resolve((0, QuickFunction_1.outcome)(UtilSymbol_1.Completed, res));
217
+ });
218
+ const timerP = timeLimit
219
+ ? new Promise((resolve) => {
220
+ const timer = setTimeout(() => resolve((0, QuickFunction_1.outcome)(UtilSymbol_1.Timeout, proc)), timeLimit); //无限制则无限时间
221
+ clearTimer = () => {
222
+ resolve((0, QuickFunction_1.outcome)(UtilSymbol_1.Timeout, proc));
223
+ clearInterval(timer);
224
+ };
225
+ })
226
+ : UtilFunc.getNeverResolvedPromise();
227
+ const result = Promise.race([procerP, timerP]);
228
+ reslove(result);
229
+ });
230
+ }
229
231
  /**部分类组合
230
232
  * 将mixin的部分字段混入base
231
233
  * @param base - 基础类
@@ -234,7 +236,7 @@ var UtilFunc;
234
236
  * @param fields - 需要混入的字段
235
237
  * @returns 混合完成的类
236
238
  */
237
- function composeClassPart(base, mixin, key, ...fields) {
239
+ static composeClassPart(base, mixin, key, ...fields) {
238
240
  const compObj = base;
239
241
  if (compObj[key] !== undefined)
240
242
  UtilLogger_1.SLogger.warn(`key: ${key} 已存在于基础类中, 混入可能导致类型问题`);
@@ -266,9 +268,8 @@ var UtilFunc;
266
268
  }
267
269
  return compObj;
268
270
  }
269
- UtilFunc.composeClassPart = composeClassPart;
270
271
  /**根据 MIXIN_FIELDS 自动混入 */
271
- function composeMixinable(base, ...mixins) {
272
+ static composeMixinable(base, ...mixins) {
272
273
  let out = base;
273
274
  const fieldsSet = new Set();
274
275
  for (const rawmixin of mixins) {
@@ -280,51 +281,37 @@ var UtilFunc;
280
281
  else
281
282
  fieldsSet.add(fixField);
282
283
  }
283
- out = composeClassPart(base, mixin, mixin.MIXIN_KEY, ...mixin.MIXIN_FIELDS);
284
+ out = UtilFunc.composeClassPart(base, mixin, mixin.MIXIN_KEY, ...mixin.MIXIN_FIELDS);
284
285
  }
285
286
  return out;
286
287
  }
287
- UtilFunc.composeMixinable = composeMixinable;
288
288
  /**对对象的每个属性应用映射函数,并返回一个新的对象。
289
289
  * @template T - 对象的类型
290
290
  * @param obj - 要处理的对象
291
291
  * @param mapper - 映射函数,接受一个值和一个键,返回一个新的值
292
292
  * @returns - 一个新的对象,它的属性是原对象的属性经过映射函数处理后的结果
293
293
  */
294
- function mapEntries(obj, mapper) {
294
+ static mapEntries(obj, mapper) {
295
295
  return Object.entries(obj).reduce((result, [key, value]) => {
296
296
  result[key] = mapper(key, value);
297
297
  return result;
298
298
  }, {});
299
299
  }
300
- UtilFunc.mapEntries = mapEntries;
301
- /**处理联合 Outcome
302
- * @param t - 目标值
303
- * @param procObj - 所有可能的id组成的处理函数映射
304
- * @returns 任意处理函数的返回值
305
- */
306
- function matchOutcome(t, procObj) {
307
- return procObj[t.status](t.status, t?.result);
308
- }
309
- UtilFunc.matchOutcome = matchOutcome;
310
- /**处理联合 字符串
311
- * @param t - 目标值
312
- * @param procObj - 所有可能的id组成的处理函数映射
313
- * @returns 任意处理函数的返回值
314
- */
315
- function matchStr(t, procObj) {
316
- return procObj[t](t);
317
- }
318
- UtilFunc.matchStr = matchStr;
319
300
  /**将JToken转换为字符串
320
301
  * @param token - 待转换的Token
321
302
  * @param space - 插入的空格 数字为空格数量 默认为制表符\t
322
303
  * @returns 转换完成的字符串
323
304
  */
324
- function stringifyJToken(token, space = "\t") {
305
+ static stringifyJToken(token, space = "\t") {
325
306
  if (space == null)
326
307
  space = undefined;
327
308
  return JSON.stringify(token, null, space);
328
309
  }
329
- UtilFunc.stringifyJToken = stringifyJToken;
330
- })(UtilFunc = exports.UtilFunc || (exports.UtilFunc = {}));
310
+ }
311
+ __decorate([
312
+ (0, UtilDecorators_1.LogTimeAsync)("repeatPromise ", true),
313
+ __metadata("design:type", Function),
314
+ __metadata("design:paramtypes", [Function, Function, Number, Number]),
315
+ __metadata("design:returntype", Promise)
316
+ ], UtilFunc, "repeatPromise", null);
317
+ exports.UtilFunc = UtilFunc;
@@ -1,3 +1,4 @@
1
+ import { Completed, Failed, Terminated } from "./UtilSymbol";
1
2
  /**可以序列化为JSON文件的对象 */
2
3
  export type JToken = JObject | JArray | JValue | IJData;
3
4
  /**在stringify输出时 undefine 会被转为 null */
@@ -14,6 +15,8 @@ export interface IJData {
14
15
  */
15
16
  toJSON(): JToken;
16
17
  }
18
+ /**任意可作为键值的类型 */
19
+ export type Keyable = string | number | symbol;
17
20
  /**转为可写的 */
18
21
  export type Writeable<T> = {
19
22
  -readonly [P in keyof T]: T[P];
@@ -53,7 +56,7 @@ export type ExclusiveJObject<B extends JObject, T extends JToken, K extends stri
53
56
  * 终止 将直接返回 null
54
57
  * 失败 将重试
55
58
  */
56
- export type PromiseStat = "Completed" | "Failed" | "Terminated";
59
+ export type PromiseStat = Completed | Failed | Terminated;
57
60
  /**promise验证函数 */
58
61
  export type PromiseVerifyFn<T> = (obj: T) => Promise<PromiseStat> | PromiseStat;
59
62
  /**类型中任意函数的字符串名称 */
@@ -107,12 +110,12 @@ export type WithPrefix<T, P extends string> = {
107
110
  * @template K - 类型键值
108
111
  * @template V - 值
109
112
  */
110
- export type Outcome<K extends string, V> = {
113
+ export type Outcome<K extends Keyable, V> = {
111
114
  /**状态类型 */
112
115
  status: K;
113
116
  /**值 */
114
117
  result: V;
115
118
  };
116
119
  /**从联合 Outcome 中 根据 id 提取对应 value 的 type */
117
- export type ExtractOutcome<T, K extends string> = T extends Outcome<K, unknown> ? T : never;
120
+ export type ExtractOutcome<T, K extends Keyable> = T extends Outcome<K, unknown> ? T : never;
118
121
  export {};
@@ -0,0 +1,15 @@
1
+ /**完成 */
2
+ export declare const Completed: unique symbol;
3
+ export type Completed = typeof Completed;
4
+ /**失败 */
5
+ export declare const Failed: unique symbol;
6
+ export type Failed = typeof Failed;
7
+ /**终止 */
8
+ export declare const Terminated: unique symbol;
9
+ export type Terminated = typeof Terminated;
10
+ /**不存在 */
11
+ export declare const None: unique symbol;
12
+ export type None = typeof None;
13
+ /**超时 */
14
+ export declare const Timeout: unique symbol;
15
+ export type Timeout = typeof Timeout;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Timeout = exports.None = exports.Terminated = exports.Failed = exports.Completed = void 0;
4
+ /**完成 */
5
+ exports.Completed = Symbol("Completed");
6
+ /**失败 */
7
+ exports.Failed = Symbol("Failed");
8
+ /**终止 */
9
+ exports.Terminated = Symbol("Terminated");
10
+ /**不存在 */
11
+ exports.None = Symbol("None");
12
+ /**超时 */
13
+ exports.Timeout = Symbol("Timeout");
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './UtilFunctions';
2
2
  export * from './UtilInterfaces';
3
+ export * from './UtilSymbol';
3
4
  export * from './UtilClass';
4
5
  export * from './UtilCom';
5
6
  export * from './UtilCodecs';
@@ -8,3 +9,4 @@ export * from './UtilDecorators';
8
9
  export * from './UtilFileTools';
9
10
  export * from './UtilLogger';
10
11
  export * from './UtilFP';
12
+ export * from './QuickFunction';
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./UtilFunctions"), exports);
18
18
  __exportStar(require("./UtilInterfaces"), exports);
19
+ __exportStar(require("./UtilSymbol"), exports);
19
20
  __exportStar(require("./UtilClass"), exports);
20
21
  __exportStar(require("./UtilCom"), exports);
21
22
  __exportStar(require("./UtilCodecs"), exports);
@@ -24,3 +25,4 @@ __exportStar(require("./UtilDecorators"), exports);
24
25
  __exportStar(require("./UtilFileTools"), exports);
25
26
  __exportStar(require("./UtilLogger"), exports);
26
27
  __exportStar(require("./UtilFP"), exports);
28
+ __exportStar(require("./QuickFunction"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zwa73/utils",
3
- "version": "1.0.77",
3
+ "version": "1.0.78",
4
4
  "description": "my utils",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -0,0 +1,36 @@
1
+ import { ExtractOutcome, Keyable, Outcome } from "./UtilInterfaces";
2
+
3
+ /**创建一个outcome */
4
+ export function outcome<K extends Keyable,V> (key:K,value:V):Outcome<K,V>{
5
+ return {status:key,result:value}
6
+ }
7
+
8
+ /**处理联合 简单值
9
+ * @param t - 目标值
10
+ * @param procObj - 所有可能的id组成的处理函数映射
11
+ * @returns 任意处理函数的返回值
12
+ */
13
+ export function match<
14
+ T extends Keyable | Outcome<Keyable, unknown>,
15
+ P extends (T extends Keyable
16
+ ? {[K in T]:(k:K)=>unknown}
17
+ : T extends Outcome<Keyable,unknown>
18
+ ? {[K in T['status']]:(k:K,v:ExtractOutcome<T,K>['result'])=>unknown}
19
+ : never)>
20
+ (t:T, procObj:P):
21
+ P extends Record<any,(...args:any)=>any>
22
+ ? {[K in keyof P]: ReturnType<P[K]>}[keyof P]
23
+ : never {
24
+ if (typeof t === 'string' || typeof t === 'number' || typeof t === 'symbol')
25
+ return (procObj as any)[t](t);
26
+ else
27
+ return (procObj as any)[t.status](t.status,t.result);
28
+ }
29
+ if(false){
30
+ let a:"asd"|"dsa" = null as any;
31
+ const r = match(a,{
32
+ "asd":(a)=>"ssa" as const,
33
+ "dsa":(b)=>"ssb" as const,
34
+ })
35
+ }
36
+
@@ -1,3 +1,4 @@
1
+ import { UtilFunc } from "./UtilFunctions";
1
2
  import { SLogger } from "./UtilLogger";
2
3
 
3
4
  type TDTg<T> =
@@ -6,6 +7,41 @@ type TDTg<T> =
6
7
  type DTg = (target:Object, propertyKey:string, descriptor:PropertyDescriptor)=>
7
8
  PropertyDescriptor;
8
9
 
10
+ /**用于打印方法运行时间
11
+ * @param flag - 时间标签
12
+ * @param suffixUID - 是否尾随uid
13
+ */
14
+ export function LogTime(flag:string,suffixUID?:boolean):DTg{
15
+ return function (target, propertyKey, descriptor){
16
+ const originalMethod = descriptor.value;
17
+ descriptor.value = function(...args:any[]){
18
+ const uid = suffixUID ? UtilFunc.genUUID() : "";
19
+ SLogger.time(flag+uid);
20
+ let result = originalMethod.apply(this, args);
21
+ SLogger.timeEnd(flag+uid);
22
+ return result;
23
+ }
24
+ return descriptor;
25
+ }
26
+ }
27
+ /**用于打印异步方法运行时间
28
+ * @param flag - 时间标签
29
+ * @param suffixUID - 是否尾随uid
30
+ */
31
+ export function LogTimeAsync(flag:string,suffixUID?:boolean):DTg{
32
+ return function (target, propertyKey, descriptor){
33
+ const originalMethod = descriptor.value;
34
+ descriptor.value = async function(...args:any[]){
35
+ const uid = suffixUID ? UtilFunc.genUUID() : "";
36
+ SLogger.time(flag+uid);
37
+ let result = await originalMethod.apply(this, args);
38
+ SLogger.timeEnd(flag+uid);
39
+ return result;
40
+ }
41
+ return descriptor;
42
+ }
43
+ }
44
+
9
45
  /**用于打印方法的调用 */
10
46
  export function LogCall():DTg{
11
47
  return function (target, propertyKey, descriptor){
@@ -162,7 +198,7 @@ class Example {
162
198
  }
163
199
  @LogCall()
164
200
  @Defer((a,b)=>null)
165
- async myMethod1(num: number,ss:string) {
201
+ static async myMethod1(num: number,ss:string) {
166
202
  return 312;
167
203
  }
168
204
  }
@@ -1,14 +1,31 @@
1
1
  import * as crypto from "crypto";
2
- import { ComposedClass, ComposedMixinable, ExtractOutcome, FuncPropNames, IJData, JObject, JToken, Mixinable, Outcome, PromiseStat, PromiseVerifyFn } from "@src/UtilInterfaces";
2
+ import { ComposedClass, ComposedMixinable, ExtractOutcome, IJData, JObject, JToken, Keyable, Mixinable, Outcome, PromiseStat, PromiseVerifyFn } from "@src/UtilInterfaces";
3
3
  import * as cp from "child_process";
4
4
  import { SLogger } from "@src/UtilLogger";
5
+ import { Completed, Failed, None, Terminated, Timeout } from "./UtilSymbol";
6
+ import { match, outcome } from "./QuickFunction";
7
+ import { LogTimeAsync } from "./UtilDecorators";
5
8
 
9
+
10
+ type CompleteCome<T> = Outcome<Completed,T>;
11
+ type TimeoutCome<T> = Outcome<Timeout,Promise<T>>;
12
+ /**永不完成的Promise单例 */
13
+ const NeverResolvedPromise = new Promise(()=>{});
14
+ /**进行中的请求 */
15
+ type ProcessingPromise<T> = {
16
+ /**主体请求 */
17
+ result:T;
18
+ /**请求状态 */
19
+ stat:PromiseStat;
20
+ /**请求下标/序号 */
21
+ index:number;
22
+ };
6
23
  /**常用函数 */
7
- export namespace UtilFunc{
24
+ export class UtilFunc{
8
25
  /**获取当前时间戳
9
26
  * @returns 时间戳
10
27
  */
11
- export function getTime(): number {
28
+ static getTime(): number {
12
29
  return new Date().getTime();
13
30
  }
14
31
 
@@ -19,7 +36,7 @@ export function getTime(): number {
19
36
  * @param defaultVal - 默认值
20
37
  * @returns 最终值
21
38
  */
22
- export function initField<T extends object,K extends keyof T>(
39
+ static initField<T extends object,K extends keyof T>(
23
40
  obj: T,
24
41
  field: K,
25
42
  defaultVal: T[K]
@@ -33,7 +50,7 @@ export function initField<T extends object,K extends keyof T>(
33
50
  * @param checkObj - 用于检测的对象 在对应key缺失时赋予对应值 如果值为函数, 则赋予执行结果 如果结果为 undefined 则不赋值
34
51
  * @returns 完成初始化的对象
35
52
  */
36
- export function initObject<T extends JObject>
53
+ static initObject<T extends JObject>
37
54
  (obj:T,checkObj:{[P in keyof T]:T[P]|(()=>void|T[P])}){
38
55
  const fixobj = obj as any;
39
56
  for(const key in checkObj){
@@ -52,14 +69,14 @@ export function initObject<T extends JObject>
52
69
  /**生成一串uuid
53
70
  * @returns uuid
54
71
  */
55
- export function genUUID() {
72
+ static genUUID() {
56
73
  return crypto.randomBytes(16).toString("hex");
57
74
  }
58
75
  /**计算Hash
59
76
  * @param str - 待计算的字符串
60
77
  * @returns hash
61
78
  */
62
- export function calcHash(str:string) {
79
+ static calcHash(str:string) {
63
80
  return crypto.createHash('md5').update(str).digest('hex');
64
81
  }
65
82
 
@@ -68,7 +85,7 @@ export function calcHash(str:string) {
68
85
  * @param obj - 克隆目标
69
86
  * @returns 克隆结果
70
87
  */
71
- export function deepClone<T extends JToken>(obj: T): T {
88
+ static deepClone<T extends JToken>(obj: T): T {
72
89
  return JSON.parse(JSON.stringify(obj));
73
90
  }
74
91
 
@@ -76,7 +93,7 @@ export function deepClone<T extends JToken>(obj: T): T {
76
93
  * @param num - 所要检测的数字
77
94
  * @returns 是否安全
78
95
  */
79
- export function isSafeNumber(num: number): boolean {
96
+ static isSafeNumber(num: number): boolean {
80
97
  if (num === undefined || num == null || isNaN(num)) return false;
81
98
  if(typeof num === 'number') return true;
82
99
  return false;
@@ -87,10 +104,18 @@ export function isSafeNumber(num: number): boolean {
87
104
  * @param timeMs - 等待的毫秒数
88
105
  * @returns
89
106
  */
90
- export async function sleep(timeMs: number): Promise<boolean> {
107
+ static async sleep<T>(timeMs: number): Promise<void>
108
+ /**等待 timeMs 毫秒
109
+ * @async
110
+ * @param timeMs - 等待的毫秒数
111
+ * @param result - 结果
112
+ * @returns
113
+ */
114
+ static async sleep<T>(timeMs: number, result:T): Promise<T>
115
+ static async sleep<T>(timeMs: number, result?:T): Promise<T|undefined> {
91
116
  return new Promise(function (resolve, rejecte) {
92
117
  let timer = setTimeout(function () {
93
- resolve(true);
118
+ resolve(result);
94
119
  }, timeMs);
95
120
  });
96
121
  }
@@ -98,7 +123,7 @@ export async function sleep(timeMs: number): Promise<boolean> {
98
123
  /**封装的 cp.exec 执行一段指令 指令完成后返回 Promise
99
124
  * @param command 指令文本
100
125
  */
101
- export function exec(command: string) {
126
+ static exec(command: string) {
102
127
  return new Promise<{ stdout:string, stderr:string }>
103
128
  ((resolve, reject) => {
104
129
  cp.exec(command, (error, stdout, stderr) => {
@@ -110,23 +135,12 @@ export function exec(command: string) {
110
135
  });
111
136
  }
112
137
 
113
- /**永不完成的Promise单例 */
114
- const NeverResolvedPromise = new Promise(()=>{});
138
+
115
139
  /**获得一个永不完成的Promise单例 */
116
- export function getNeverResolvedPromise<T>():Promise<T>{
140
+ static getNeverResolvedPromise<T>():Promise<T>{
117
141
  return NeverResolvedPromise as Promise<T>;
118
142
  }
119
143
 
120
- /**进行中的请求 */
121
- type ProcessingPromise<T> = {
122
- /**主体请求 */
123
- result:T;
124
- /**请求状态 */
125
- stat:PromiseStat|Promise<PromiseStat>;
126
- /**请求下标/序号 */
127
- index:number;
128
- };
129
-
130
144
  /**重复尝试promise
131
145
  * @async
132
146
  * @param procFn - 发起函数
@@ -135,13 +149,10 @@ type ProcessingPromise<T> = {
135
149
  * @param repeatTime - 超时时间/秒 最小为10秒
136
150
  * @returns 结果 null 为全部失败/超时
137
151
  */
138
- export async function repeatPromise<T>(procFn:()=>Promise<T>,verifyFn?:PromiseVerifyFn<T>,
152
+ @LogTimeAsync("repeatPromise ",true)
153
+ static async repeatPromise<T>(procFn:()=>Promise<T>,verifyFn?:PromiseVerifyFn<T>,
139
154
  repeatCount:number=3,repeatTime:number=180):Promise<T|null>{
140
155
 
141
- //计时
142
- const timeflag = "repeatPromise "+UtilFunc.genUUID();
143
- SLogger.time(timeflag);
144
-
145
156
  /**是否含有超时时间 */
146
157
  const hasRepeatTime = (repeatTime>=10);
147
158
  //转换为毫秒
@@ -149,23 +160,13 @@ export async function repeatPromise<T>(procFn:()=>Promise<T>,verifyFn?:PromiseVe
149
160
 
150
161
  //验证处理函数
151
162
  if(verifyFn===undefined)
152
- verifyFn = ()=>"Completed";
153
-
154
- /**计时器 */
155
- let timer:NodeJS.Timer|null = null;
156
- /**计时器 Promise */
157
- let timerP:Promise<"Timeout">|null=null;
158
- /**计时器 Promise 的返回函数 */
159
- let resolveFn:((value: "Timeout")=>void)|null = null;
160
- /**清理计时器 */
161
- const clearTimer = ()=>{
162
- if(timer) clearInterval(timer);
163
- if(resolveFn) resolveFn("Timeout");
164
- timerP = timer = resolveFn = null;
165
- }
163
+ verifyFn = ()=>Completed;
166
164
 
167
165
  //进行中的请求
168
- const plist:Promise<ProcessingPromise<T>>[] = [];
166
+ const plist:Promise<
167
+ CompleteCome<ProcessingPromise<T>>|
168
+ TimeoutCome<ProcessingPromise<T>>
169
+ >[] = [];
169
170
 
170
171
  //开始处理
171
172
  try{
@@ -175,57 +176,57 @@ export async function repeatPromise<T>(procFn:()=>Promise<T>,verifyFn?:PromiseVe
175
176
 
176
177
  //如果 plist 中当前下标的任务还未创建 则 创建当前任务
177
178
  if(plist.length<i+1){
178
- plist.push(procFn().then(result =>
179
- ({result, stat:verifyFn!(result), index:i})));
180
- }
181
-
182
- //创建定时器
183
- if(timerP==null){
184
- timerP = new Promise<"Timeout">((resolve, rejecte)=>{
185
- resolveFn = resolve;
186
- timer = setTimeout(()=>resolve("Timeout"),
187
- hasRepeatTime ? repeatTime : Infinity);//无限制则无限时间
188
- })
179
+ plist.push(UtilFunc.timelimitPromise<ProcessingPromise<T>>(async ()=>{
180
+ const result = await procFn();
181
+ const stat = await verifyFn!(result);
182
+ return {result, stat, index:i}
183
+ }));
189
184
  }
190
185
 
191
186
  //等待任意任务 或当前计时器完成
192
- const currObj = await Promise.race([...plist, timerP]);
187
+ const currObj = await Promise.race([...plist]);
193
188
 
194
189
  //超时处理
195
- if(currObj==="Timeout"){
190
+ if(currObj.status===Timeout){
191
+ //解除timeout替换原参数
192
+ plist[i]=new Promise(async (rslove)=>{
193
+ const res = await currObj.result;
194
+ rslove(outcome(Completed,res));
195
+ })
196
196
  SLogger.warn(`第 ${i+1} 次 repeatPromise 超时 ${repeatTime} ms 开始重试`);
197
- clearTimer(); i++;
197
+ i++;
198
198
  continue;
199
199
  }
200
200
 
201
201
  //路由请求状态
202
- const poststat = await currObj.stat;
203
- const result = matchStr(poststat,{
204
- Completed(){
205
- SLogger.info(`第 ${currObj.index+1} 次 repeatPromise 成功`);
202
+ const postresult = currObj.result;
203
+ const result = match(postresult.stat,{
204
+ [Completed](){
205
+ SLogger.info(`第 ${postresult.index+1} 次 repeatPromise 成功`);
206
206
  //非当前
207
- if(currObj.index!=i)
207
+ if(postresult.index!=i)
208
208
  SLogger.info(`成功的 promise 非当前 promise 考虑增大重试间隔\n当前index: ${i}\n当前间隔: ${repeatTime}`);
209
- return currObj.result;
209
+ return postresult.result;
210
210
  },
211
- Terminated(){
212
- SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 终止 停止重试`);
213
- return currObj.result;
211
+ [Terminated](){
212
+ SLogger.warn(`第 ${postresult.index+1} 次 repeatPromise 终止 停止重试`);
213
+ return postresult.result;
214
214
  },
215
- Failed(){
215
+ [Failed]():None{
216
216
  //抛弃失败
217
- plist[currObj.index] = UtilFunc.getNeverResolvedPromise();
217
+ plist[postresult.index] = UtilFunc.getNeverResolvedPromise();
218
218
  //是当前
219
- if(currObj.index==i){
220
- SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 失败 开始重试`);
221
- clearTimer(); i++;
222
- return;
219
+ if(postresult.index==i){
220
+ SLogger.warn(`第 ${postresult.index+1} 次 repeatPromise 失败 开始重试`);
221
+ i++;
222
+ return None;
223
223
  }
224
224
  //非当前
225
- SLogger.warn(`第 ${currObj.index+1} 次 repeatPromise 失败`);
225
+ SLogger.warn(`第 ${postresult.index+1} 次 repeatPromise 失败`);
226
+ return None;
226
227
  },
227
228
  });
228
- if(result !== undefined) return result;
229
+ if(result !== None) return result;
229
230
  }
230
231
  //全部失败或超时则返回null
231
232
  SLogger.warn(`${repeatCount} 次 repeatPromise 尝试均失败`);
@@ -233,13 +234,47 @@ export async function repeatPromise<T>(procFn:()=>Promise<T>,verifyFn?:PromiseVe
233
234
  }catch(err){
234
235
  SLogger.warn(`repeatPromise 发生错误`,err);
235
236
  return null;
236
- }finally{
237
- //清理
238
- clearTimer();
239
- SLogger.timeEnd(timeflag);
240
237
  }
241
238
  }
242
239
 
240
+
241
+ /**创建一个限时的Promise
242
+ * @param func - 处理函数
243
+ * @param timeLimit - 毫秒限时
244
+ * @returns 超时则返回 处理函数委托 完成则返回结果
245
+ */
246
+ static timelimitPromise<T>
247
+ (func:()=>Promise<T>|T,timeLimit?:number):Promise<CompleteCome<T>|TimeoutCome<T>>{
248
+ return new Promise<CompleteCome<T>|TimeoutCome<T>>((reslove)=>{
249
+ let clearTimer:(()=>void)| null = null;
250
+ let proc = (async ()=>await func())();
251
+
252
+ const procerP = new Promise<CompleteCome<T>>(async (resolve)=>{
253
+ const res = await proc;
254
+ if(clearTimer) clearTimer();
255
+ resolve(outcome(Completed,res))
256
+ });
257
+
258
+ const timerP = timeLimit
259
+ ? new Promise<TimeoutCome<T>>((resolve)=>{
260
+ const timer = setTimeout(()=>
261
+ resolve(outcome(Timeout,proc))
262
+ ,timeLimit);//无限制则无限时间
263
+
264
+ clearTimer = ()=>{
265
+ resolve(outcome(Timeout,proc))
266
+ clearInterval(timer)
267
+ }
268
+ })
269
+ : UtilFunc.getNeverResolvedPromise<TimeoutCome<T>>();
270
+
271
+ const result = Promise.race([procerP,timerP]);
272
+ reslove(result);
273
+ })
274
+ }
275
+
276
+
277
+
243
278
  /**部分类组合
244
279
  * 将mixin的部分字段混入base
245
280
  * @param base - 基础类
@@ -248,7 +283,7 @@ export async function repeatPromise<T>(procFn:()=>Promise<T>,verifyFn?:PromiseVe
248
283
  * @param fields - 需要混入的字段
249
284
  * @returns 混合完成的类
250
285
  */
251
- export function composeClassPart
286
+ static composeClassPart
252
287
  <Base extends object,Mixin extends object,Field extends keyof Mixin>
253
288
  (base:Base,mixin:Mixin,key:string,...fields:Field[]):ComposedClass<Base,Mixin,typeof key,Field>{
254
289
  const compObj = base as any;
@@ -283,7 +318,7 @@ export function composeClassPart
283
318
  }
284
319
 
285
320
  /**根据 MIXIN_FIELDS 自动混入 */
286
- export function composeMixinable
321
+ static composeMixinable
287
322
  <Base extends object, Mixins extends Mixinable<any>[]>
288
323
  (base:Base,...mixins:Mixins):
289
324
  ComposedMixinable<Base,Mixins>{
@@ -298,7 +333,7 @@ export function composeMixinable
298
333
  else
299
334
  fieldsSet.add(fixField);
300
335
  }
301
- out = composeClassPart(base,mixin,mixin.MIXIN_KEY,...mixin.MIXIN_FIELDS);
336
+ out = UtilFunc.composeClassPart(base,mixin,mixin.MIXIN_KEY,...mixin.MIXIN_FIELDS);
302
337
  }
303
338
  return out as any;
304
339
  }
@@ -310,7 +345,7 @@ export function composeMixinable
310
345
  * @param mapper - 映射函数,接受一个值和一个键,返回一个新的值
311
346
  * @returns - 一个新的对象,它的属性是原对象的属性经过映射函数处理后的结果
312
347
  */
313
- export function mapEntries<T extends Object>
348
+ static mapEntries<T extends Object>
314
349
  (obj: T, mapper: (key: keyof T, value: T[keyof T]) => T[keyof T]): T {
315
350
  return Object.entries(obj).reduce((result, [key, value]) => {
316
351
  result[key as keyof T] = mapper(key as keyof T, value);
@@ -318,33 +353,12 @@ export function mapEntries<T extends Object>
318
353
  }, {} as T);
319
354
  }
320
355
 
321
- /**处理联合 Outcome
322
- * @param t - 目标值
323
- * @param procObj - 所有可能的id组成的处理函数映射
324
- * @returns 任意处理函数的返回值
325
- */
326
- export function matchOutcome<
327
- T extends Outcome<string,unknown>,
328
- P extends {[K in T['status']]:(k:K,v:ExtractOutcome<T,K>['result'])=>unknown}>
329
- (t:T,procObj:P):{[K in keyof P]:ReturnType<P[K]>}[keyof P]{
330
- return (procObj as any)[t.status](t.status,(t as any)?.result)
331
- }
332
- /**处理联合 字符串
333
- * @param t - 目标值
334
- * @param procObj - 所有可能的id组成的处理函数映射
335
- * @returns 任意处理函数的返回值
336
- */
337
- export function matchStr<T extends string,P extends {[K in T]:(k:K)=>unknown}>
338
- (t:T,procObj:P):{[K in keyof P]:ReturnType<P[K]>}[keyof P]{
339
- return (procObj as any)[t](t)
340
- }
341
-
342
356
  /**将JToken转换为字符串
343
357
  * @param token - 待转换的Token
344
358
  * @param space - 插入的空格 数字为空格数量 默认为制表符\t
345
359
  * @returns 转换完成的字符串
346
360
  */
347
- export function stringifyJToken(token:JToken|IJData,space:string|number|null|undefined="\t"){
361
+ static stringifyJToken(token:JToken|IJData,space:string|number|null|undefined="\t"){
348
362
  if(space==null)
349
363
  space=undefined;
350
364
  return JSON.stringify(token,null,space);
@@ -1,3 +1,4 @@
1
+ import { Completed, Failed, Terminated } from "./UtilSymbol";
1
2
 
2
3
 
3
4
  /**可以序列化为JSON文件的对象 */
@@ -17,6 +18,9 @@ export interface IJData{
17
18
  toJSON():JToken;
18
19
  }
19
20
 
21
+ /**任意可作为键值的类型 */
22
+ export type Keyable = string | number | symbol;
23
+
20
24
  /**转为可写的 */
21
25
  export type Writeable<T> = {
22
26
  -readonly [P in keyof T]: T[P]
@@ -67,7 +71,7 @@ export type ExclusiveJObject<B extends JObject,T extends JToken,K extends string
67
71
  * 终止 将直接返回 null
68
72
  * 失败 将重试
69
73
  */
70
- export type PromiseStat = "Completed"|"Failed"|"Terminated";
74
+ export type PromiseStat = Completed|Failed|Terminated;
71
75
  /**promise验证函数 */
72
76
  export type PromiseVerifyFn<T> = (obj:T)=>Promise<PromiseStat>|PromiseStat;
73
77
 
@@ -139,7 +143,7 @@ export type WithPrefix<T,P extends string> = {
139
143
  * @template K - 类型键值
140
144
  * @template V - 值
141
145
  */
142
- export type Outcome<K extends string,V> = {
146
+ export type Outcome<K extends Keyable,V> = {
143
147
  /**状态类型 */
144
148
  status:K;
145
149
  /**值 */
@@ -147,6 +151,6 @@ export type Outcome<K extends string,V> = {
147
151
  }
148
152
 
149
153
  /**从联合 Outcome 中 根据 id 提取对应 value 的 type */
150
- export type ExtractOutcome<T,K extends string> =
154
+ export type ExtractOutcome<T,K extends Keyable> =
151
155
  T extends Outcome<K,unknown> ? T : never;
152
156
 
@@ -0,0 +1,15 @@
1
+ /**完成 */
2
+ export const Completed = Symbol("Completed");
3
+ export type Completed = typeof Completed;
4
+ /**失败 */
5
+ export const Failed = Symbol("Failed");
6
+ export type Failed = typeof Failed;
7
+ /**终止 */
8
+ export const Terminated = Symbol("Terminated");
9
+ export type Terminated = typeof Terminated;
10
+ /**不存在 */
11
+ export const None = Symbol("None");
12
+ export type None = typeof None;
13
+ /**超时 */
14
+ export const Timeout = Symbol("Timeout");
15
+ export type Timeout = typeof Timeout;
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './UtilFunctions';
2
2
  export * from './UtilInterfaces';
3
+ export * from './UtilSymbol';
3
4
  export * from './UtilClass';
4
5
  export * from './UtilCom';
5
6
  export * from './UtilCodecs';
@@ -7,4 +8,5 @@ export * from './UtilFfmpegTools';
7
8
  export * from './UtilDecorators';
8
9
  export * from './UtilFileTools';
9
10
  export * from './UtilLogger';
10
- export * from './UtilFP';
11
+ export * from './UtilFP';
12
+ export * from './QuickFunction';