@zwa73/utils 1.0.193 → 1.0.194

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.
@@ -1,4 +1,4 @@
1
1
  import { UtilFT } from "./UtilFileTools";
2
2
  import { UtilFunc } from "./UtilFunctions";
3
- export declare const outcome: typeof UtilFunc.outcome, matchProc: typeof UtilFunc.matchProc, sucesProc: typeof UtilFunc.sucesProc, isFailed: typeof UtilFunc.isFailed, isSafeNumber: typeof UtilFunc.isSafeNumber, isSuccess: typeof UtilFunc.isSuccess, likeNone: typeof UtilFunc.likeNone, expect: typeof UtilFunc.expect, assertType: typeof UtilFunc.assertType, assertLiteral: typeof UtilFunc.assertLiteral, deepClone: typeof UtilFunc.deepClone, sleep: typeof UtilFunc.sleep, stringifyJToken: typeof UtilFunc.stringifyJToken, getTime: typeof UtilFunc.getTime, mapEntries: typeof UtilFunc.mapEntries, dedent: typeof UtilFunc.dedent, throwError: typeof UtilFunc.throwError, eitherize: typeof UtilFunc.eitherize, taskEitherize: typeof UtilFunc.taskEitherize, memoize: typeof UtilFunc.memoize;
3
+ export declare const outcome: typeof UtilFunc.outcome, matchProc: typeof UtilFunc.matchProc, sucesProc: typeof UtilFunc.sucesProc, isFailed: typeof UtilFunc.isFailed, isSafeNumber: typeof UtilFunc.isSafeNumber, isSuccess: typeof UtilFunc.isSuccess, likeNone: typeof UtilFunc.likeNone, expect: typeof UtilFunc.expect, assertType: typeof UtilFunc.assertType, assertLiteral: typeof UtilFunc.assertLiteral, deepClone: typeof UtilFunc.deepClone, sleep: typeof UtilFunc.sleep, stringifyJToken: typeof UtilFunc.stringifyJToken, getTime: typeof UtilFunc.getTime, mapEntries: typeof UtilFunc.mapEntries, dedent: typeof UtilFunc.dedent, throwError: typeof UtilFunc.throwError, eitherize: typeof UtilFunc.eitherize, taskEitherize: typeof UtilFunc.taskEitherize, memoize: typeof UtilFunc.memoize, ivk: typeof UtilFunc.ivk, l2s: typeof UtilFunc.l2s, s2l: typeof UtilFunc.s2l;
4
4
  export declare const stylizePath: typeof UtilFT.stylizePath, posixizePath: typeof UtilFT.posixizePath, win32izePath: typeof UtilFT.win32izePath, currosizePath: typeof UtilFT.currosizePath;
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.currosizePath = exports.win32izePath = exports.posixizePath = exports.stylizePath = exports.memoize = exports.taskEitherize = exports.eitherize = exports.throwError = exports.dedent = exports.mapEntries = exports.getTime = exports.stringifyJToken = exports.sleep = exports.deepClone = exports.assertLiteral = exports.assertType = exports.expect = exports.likeNone = exports.isSuccess = exports.isSafeNumber = exports.isFailed = exports.sucesProc = exports.matchProc = exports.outcome = void 0;
3
+ exports.currosizePath = exports.win32izePath = exports.posixizePath = exports.stylizePath = exports.s2l = exports.l2s = exports.ivk = exports.memoize = exports.taskEitherize = exports.eitherize = exports.throwError = exports.dedent = exports.mapEntries = exports.getTime = exports.stringifyJToken = exports.sleep = exports.deepClone = exports.assertLiteral = exports.assertType = exports.expect = exports.likeNone = exports.isSuccess = exports.isSafeNumber = exports.isFailed = exports.sucesProc = exports.matchProc = exports.outcome = void 0;
4
4
  const UtilFileTools_1 = require("./UtilFileTools");
5
5
  const UtilFunctions_1 = require("./UtilFunctions");
6
6
  const UtilSymbol_1 = require("./UtilSymbol");
7
- exports.outcome = UtilFunctions_1.UtilFunc.outcome, exports.matchProc = UtilFunctions_1.UtilFunc.matchProc, exports.sucesProc = UtilFunctions_1.UtilFunc.sucesProc, exports.isFailed = UtilFunctions_1.UtilFunc.isFailed, exports.isSafeNumber = UtilFunctions_1.UtilFunc.isSafeNumber, exports.isSuccess = UtilFunctions_1.UtilFunc.isSuccess, exports.likeNone = UtilFunctions_1.UtilFunc.likeNone, exports.expect = UtilFunctions_1.UtilFunc.expect, exports.assertType = UtilFunctions_1.UtilFunc.assertType, exports.assertLiteral = UtilFunctions_1.UtilFunc.assertLiteral, exports.deepClone = UtilFunctions_1.UtilFunc.deepClone, exports.sleep = UtilFunctions_1.UtilFunc.sleep, exports.stringifyJToken = UtilFunctions_1.UtilFunc.stringifyJToken, exports.getTime = UtilFunctions_1.UtilFunc.getTime, exports.mapEntries = UtilFunctions_1.UtilFunc.mapEntries, exports.dedent = UtilFunctions_1.UtilFunc.dedent, exports.throwError = UtilFunctions_1.UtilFunc.throwError, exports.eitherize = UtilFunctions_1.UtilFunc.eitherize, exports.taskEitherize = UtilFunctions_1.UtilFunc.taskEitherize, exports.memoize = UtilFunctions_1.UtilFunc.memoize;
7
+ exports.outcome = UtilFunctions_1.UtilFunc.outcome, exports.matchProc = UtilFunctions_1.UtilFunc.matchProc, exports.sucesProc = UtilFunctions_1.UtilFunc.sucesProc, exports.isFailed = UtilFunctions_1.UtilFunc.isFailed, exports.isSafeNumber = UtilFunctions_1.UtilFunc.isSafeNumber, exports.isSuccess = UtilFunctions_1.UtilFunc.isSuccess, exports.likeNone = UtilFunctions_1.UtilFunc.likeNone, exports.expect = UtilFunctions_1.UtilFunc.expect, exports.assertType = UtilFunctions_1.UtilFunc.assertType, exports.assertLiteral = UtilFunctions_1.UtilFunc.assertLiteral, exports.deepClone = UtilFunctions_1.UtilFunc.deepClone, exports.sleep = UtilFunctions_1.UtilFunc.sleep, exports.stringifyJToken = UtilFunctions_1.UtilFunc.stringifyJToken, exports.getTime = UtilFunctions_1.UtilFunc.getTime, exports.mapEntries = UtilFunctions_1.UtilFunc.mapEntries, exports.dedent = UtilFunctions_1.UtilFunc.dedent, exports.throwError = UtilFunctions_1.UtilFunc.throwError, exports.eitherize = UtilFunctions_1.UtilFunc.eitherize, exports.taskEitherize = UtilFunctions_1.UtilFunc.taskEitherize, exports.memoize = UtilFunctions_1.UtilFunc.memoize, exports.ivk = UtilFunctions_1.UtilFunc.ivk, exports.l2s = UtilFunctions_1.UtilFunc.l2s, exports.s2l = UtilFunctions_1.UtilFunc.s2l;
8
8
  exports.stylizePath = UtilFileTools_1.UtilFT.stylizePath, exports.posixizePath = UtilFileTools_1.UtilFT.posixizePath, exports.win32izePath = UtilFileTools_1.UtilFT.win32izePath, exports.currosizePath = UtilFileTools_1.UtilFT.currosizePath;
9
9
  if (false) {
10
10
  let aaser = (0, exports.assertLiteral)({ a: 1 });
package/dist/UtilClass.js CHANGED
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Hbs = exports.Stream = exports.Piper = void 0;
7
- const QuickFunction_1 = require("./QuickFunction");
7
+ const QuickExport_1 = require("./QuickExport");
8
8
  const handlebars_1 = __importDefault(require("handlebars"));
9
9
  const UtilLogger_1 = require("./UtilLogger");
10
10
  /**函数管道器 */
@@ -74,7 +74,7 @@ class Stream {
74
74
  return [[...this]];
75
75
  const size = this.length;
76
76
  const result = [];
77
- (0, QuickFunction_1.matchProc)(mode, {
77
+ (0, QuickExport_1.matchProc)(mode, {
78
78
  //轮询平均分
79
79
  'average': () => {
80
80
  for (let i = 0; i < count; i++) {
package/dist/UtilFP.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UtilFP = void 0;
4
- const QuickFunction_1 = require("./QuickFunction");
4
+ const QuickExport_1 = require("./QuickExport");
5
5
  /**常用函数式编程库 */
6
6
  var UtilFP;
7
7
  (function (UtilFP) {
@@ -55,9 +55,9 @@ var UtilFP;
55
55
  }
56
56
  UtilFP.map = map;
57
57
  /**创建在传入值为失败时不运行的函数 */
58
- UtilFP.chain = (f) => (arg) => (0, QuickFunction_1.isFailed)(arg) ? arg : f(arg);
58
+ UtilFP.chain = (f) => (arg) => (0, QuickExport_1.isFailed)(arg) ? arg : f(arg);
59
59
  /**创建在传入值为失败时才会尝试运行的函数 */
60
- UtilFP.alt = (f) => (arg) => (0, QuickFunction_1.isFailed)(arg) ? f(arg) : arg;
60
+ UtilFP.alt = (f) => (arg) => (0, QuickExport_1.isFailed)(arg) ? f(arg) : arg;
61
61
  /**
62
62
  let asd = bindTo("sss",123,{abc:223});//?
63
63
  let sumvoid = ()=>10;
@@ -32,7 +32,7 @@ const pathe_1 = __importDefault(require("pathe"));
32
32
  const fs = __importStar(require("fs"));
33
33
  const UtilLogger_1 = require("./UtilLogger");
34
34
  const UtilClass_1 = require("./UtilClass");
35
- const QuickFunction_1 = require("./QuickFunction");
35
+ const QuickExport_1 = require("./QuickExport");
36
36
  /**ffmpeg工具类
37
37
  */
38
38
  class SFfmpegTool {
@@ -193,11 +193,11 @@ class SFfmpegTool {
193
193
  static async isMono(filePath) {
194
194
  const metadata = await SFfmpegTool.getAudioMetaData(filePath);
195
195
  if (metadata == null)
196
- (0, QuickFunction_1.throwError)("SFfmpegTool.isMono 获取音频元数据失败");
196
+ (0, QuickExport_1.throwError)("SFfmpegTool.isMono 获取音频元数据失败");
197
197
  // 检查音频流的声道数
198
198
  const audioStream = metadata.streams.find(stream => stream.codec_type === 'audio');
199
199
  if (audioStream == null)
200
- (0, QuickFunction_1.throwError)("SFfmpegTool.isMono 未找到音频流");
200
+ (0, QuickExport_1.throwError)("SFfmpegTool.isMono 未找到音频流");
201
201
  return audioStream.channels === 1;
202
202
  }
203
203
  //多线程处理
@@ -141,66 +141,6 @@ export declare class UtilFunc {
141
141
  * @returns 转换完成的字符串
142
142
  */
143
143
  static stringifyJToken(token: JToken | IJData, opt?: StringifyOpt): string;
144
- /**代办表 用于队列处理等待 */
145
- static pendingMap: Record<Keyable, AnyFunc[]>;
146
- /**队列处理
147
- * 等待标签为 flag 的队列
148
- * 直到排在之前的任务全部完成再处理当前Promise
149
- * @param flag - 队列标签
150
- * @param task - 任务逻辑
151
- * @returns 处理结果
152
- */
153
- static queueProc<T>(flag: Keyable, task: () => Promise<T>): Promise<T>;
154
- /**队列获取目标的代办事件数
155
- * @param flag - 队列标签
156
- */
157
- static queueLength(flag: Keyable): number;
158
- /**创建一个Outcome */
159
- static outcome<K extends Keyable, V>(key: K, value: V): Outcome<K, V>;
160
- /**处理联合值
161
- * @param t - 目标值
162
- * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
163
- * @returns 任意处理函数的返回值
164
- */
165
- static matchProc<T extends Matchable<Keyable>, P extends UnionToIntersection<{
166
- [K in MatchableFlag<T>]: (k: K, v: ExtractOutcome<T, MatchableFlag<K>>['result']) => unknown;
167
- }>>(t: T, procObj: P): P extends Record<any, AnyFunc> ? {
168
- [K in keyof P]: ReturnType<P[K]>;
169
- }[keyof P] : never;
170
- /**处理部分联合值
171
- * @param t - 目标值
172
- * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
173
- * @returns 任意处理函数的返回值
174
- */
175
- static matchPartialProc<T extends Matchable<Keyable>, P extends Partial<{
176
- [K in MatchableFlag<T>]: (k: K, v: ExtractOutcome<T, MatchableFlag<K>>['result']) => unknown;
177
- }>>(t: T, procObj: P): (P extends PRecord<Keyable, AnyFunc> ? {
178
- [K in keyof P]: P[K] extends AnyFunc ? ReturnType<P[K]> : undefined;
179
- }[keyof P] : never) | undefined;
180
- /**根据典型的成功或失败状态运行函数
181
- * @param t - 目标值
182
- * @param sucessFunc - 成功则运行的函数 (result)=>any
183
- * @param failedFunc - 失败则运行的函数 (result)=>any
184
- * @param noneFunc - 无结果或不匹配时运行的函数 ()=>any
185
- * @returns 非成功或失败时返回 None
186
- */
187
- static sucesProc<T extends Matchable<StatusSymbol>, S extends (arg: ExtractOutcome<T, SuccessLike>['result']) => unknown, F extends (arg: ExtractOutcome<T, FailedLike>['result']) => unknown = (arg: ExtractOutcome<T, FailedLike>['result']) => None, N extends () => unknown = () => None>(t: T, sucessFunc: S, failedFunc?: F, noneFunc?: N): ReturnType<S> | ReturnType<F> | ReturnType<N>;
188
- /**是失败的 */
189
- static isFailed<T>(tg: T): 'E' extends ProperSubsetCheck<symbol, T> ? boolean : T extends Matchable<FailedLike> ? true : MatchableFlag<T> extends Exclude<MatchableFlag<T>, FailedLike> ? false : boolean;
190
- /**是成功的 */
191
- static isSuccess<T>(tg: T): 'E' extends ProperSubsetCheck<symbol, T> ? boolean : T extends Matchable<SuccessLike> ? true : MatchableFlag<T> extends Exclude<MatchableFlag<T>, SuccessLike> ? false : boolean;
192
- /**类似空值 undefined null None
193
- * @param t - 检测目标
194
- * @param strictLog - 应该严格等于None 否则将输出警告 但任然返回true
195
- */
196
- static likeNone(t: unknown, strictLog?: boolean): t is None;
197
- /**验证一个值是否为空
198
- * 为空则抛异
199
- * @param t - 验证目标
200
- * @param errLog - 异常信息
201
- * @returns 排除None的原值
202
- */
203
- static expect<T>(t: T, errLog?: string): Exclude<T, None>;
204
144
  /**验证一个变量的类型是否为 T
205
145
  * @template T - 验证类型
206
146
  * @param t - 验证目标
@@ -259,16 +199,6 @@ export declare class UtilFunc {
259
199
  private static publicIp?;
260
200
  /**获取当前公网ipv4 */
261
201
  static getPublicIpv4(): Promise<string>;
262
- /**将传入函数包装为显式处理错误的函数
263
- * @param func - 待转换函数
264
- * @returns 转换完成的函数
265
- */
266
- static eitherize<T extends AnyFunc>(func: T): (...args: Parameters<T>) => Outcome<typeof Success, ReturnType<T>> | Outcome<typeof Failed, Error>;
267
- /**将传入的异步函数包装为显式处理错误的函数
268
- * @param func - 待转换函数
269
- * @returns 转换完成的函数
270
- */
271
- static taskEitherize<T extends (...args: any) => Promise<any>>(func: T): (...args: Parameters<T>) => Promise<Outcome<typeof Failed, Error> | Outcome<typeof Success, Awaited<ReturnType<T>>>>;
272
202
  /**动态导入模块的函数。这个函数是为了在TypeScript的模块系统配置为CommonJS时,防止动态import被转译为require而设计的。
273
203
  * 使用这个函数,你可以在TypeScript中动态地导入模块,而不需要担心import()被转译为require()。
274
204
  * 请注意,这个函数使用了eval(),可能会带来安全风险。
@@ -298,6 +228,76 @@ export declare class UtilFunc {
298
228
  * @returns 返回一个新的函数,这个函数在调用时会尝试从缓存中获取结果,如果缓存不存在或已过期,就会调用原函数并缓存其结果。
299
229
  */
300
230
  static memoize<T extends (...args: any[]) => any>(fn: T, expiry?: number): T extends (...args: infer In) => any ? AllExtends<In, JToken> extends true ? T : never : never;
231
+ /**代办表 用于队列处理等待 */
232
+ static pendingMap: Record<Keyable, AnyFunc[]>;
233
+ /**队列处理
234
+ * 等待标签为 flag 的队列
235
+ * 直到排在之前的任务全部完成再处理当前Promise
236
+ * @param flag - 队列标签
237
+ * @param task - 任务逻辑
238
+ * @returns 处理结果
239
+ */
240
+ static queueProc<T>(flag: Keyable, task: () => Promise<T>): Promise<T>;
241
+ /**队列获取目标的代办事件数
242
+ * @param flag - 队列标签
243
+ */
244
+ static queueLength(flag: Keyable): number;
245
+ /**创建一个Outcome */
246
+ static outcome<K extends Keyable, V>(key: K, value: V): Outcome<K, V>;
247
+ /**处理联合值
248
+ * @param t - 目标值
249
+ * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
250
+ * @returns 任意处理函数的返回值
251
+ */
252
+ static matchProc<T extends Matchable<Keyable>, P extends UnionToIntersection<{
253
+ [K in MatchableFlag<T>]: (k: K, v: ExtractOutcome<T, MatchableFlag<K>>['result']) => unknown;
254
+ }>>(t: T, procObj: P): P extends Record<any, AnyFunc> ? {
255
+ [K in keyof P]: ReturnType<P[K]>;
256
+ }[keyof P] : never;
257
+ /**处理部分联合值
258
+ * @param t - 目标值
259
+ * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
260
+ * @returns 任意处理函数的返回值
261
+ */
262
+ static matchPartialProc<T extends Matchable<Keyable>, P extends Partial<{
263
+ [K in MatchableFlag<T>]: (k: K, v: ExtractOutcome<T, MatchableFlag<K>>['result']) => unknown;
264
+ }>>(t: T, procObj: P): (P extends PRecord<Keyable, AnyFunc> ? {
265
+ [K in keyof P]: P[K] extends AnyFunc ? ReturnType<P[K]> : undefined;
266
+ }[keyof P] : never) | undefined;
267
+ /**根据典型的成功或失败状态运行函数
268
+ * @param t - 目标值
269
+ * @param sucessFunc - 成功则运行的函数 (result)=>any
270
+ * @param failedFunc - 失败则运行的函数 (result)=>any
271
+ * @param noneFunc - 无结果或不匹配时运行的函数 ()=>any
272
+ * @returns 非成功或失败时返回 None
273
+ */
274
+ static sucesProc<T extends Matchable<StatusSymbol>, S extends (arg: ExtractOutcome<T, SuccessLike>['result']) => unknown, F extends (arg: ExtractOutcome<T, FailedLike>['result']) => unknown = (arg: ExtractOutcome<T, FailedLike>['result']) => None, N extends () => unknown = () => None>(t: T, sucessFunc: S, failedFunc?: F, noneFunc?: N): ReturnType<S> | ReturnType<F> | ReturnType<N>;
275
+ /**是失败的 */
276
+ static isFailed<T>(tg: T): 'E' extends ProperSubsetCheck<symbol, T> ? boolean : T extends Matchable<FailedLike> ? true : MatchableFlag<T> extends Exclude<MatchableFlag<T>, FailedLike> ? false : boolean;
277
+ /**是成功的 */
278
+ static isSuccess<T>(tg: T): 'E' extends ProperSubsetCheck<symbol, T> ? boolean : T extends Matchable<SuccessLike> ? true : MatchableFlag<T> extends Exclude<MatchableFlag<T>, SuccessLike> ? false : boolean;
279
+ /**类似空值 undefined null None
280
+ * @param t - 检测目标
281
+ * @param strictLog - 应该严格等于None 否则将输出警告 但任然返回true
282
+ */
283
+ static likeNone(t: unknown, strictLog?: boolean): t is None;
284
+ /**验证一个值是否为空
285
+ * 为空则抛异
286
+ * @param t - 验证目标
287
+ * @param errLog - 异常信息
288
+ * @returns 排除None的原值
289
+ */
290
+ static expect<T>(t: T, errLog?: string): Exclude<T, None>;
291
+ /**将传入函数包装为显式处理错误的函数
292
+ * @param func - 待转换函数
293
+ * @returns 转换完成的函数
294
+ */
295
+ static eitherize<T extends AnyFunc>(func: T): (...args: Parameters<T>) => Outcome<typeof Success, ReturnType<T>> | Outcome<typeof Failed, Error>;
296
+ /**将传入的异步函数包装为显式处理错误的函数
297
+ * @param func - 待转换函数
298
+ * @returns 转换完成的函数
299
+ */
300
+ static taskEitherize<T extends (...args: any) => Promise<any>>(func: T): (...args: Parameters<T>) => Promise<Outcome<typeof Failed, Error> | Outcome<typeof Success, Awaited<ReturnType<T>>>>;
301
301
  /**将hh:mm:ss,ms格式转换为毫秒 */
302
302
  static parseSrtTime(time: string): number;
303
303
  /**将毫秒转换为hh:mm:ss,ms格式 */
@@ -306,5 +306,14 @@ export declare class UtilFunc {
306
306
  static parseSrt(srtText: string): SrtSegment[];
307
307
  /**转换json为srt文本 */
308
308
  static createSrt(segments: SrtSegment[]): string;
309
+ /**立即执行传入的函数
310
+ * @param fn - 需要立即执行的函数。
311
+ * @returns 返回 fn 函数的执行结果。
312
+ */
313
+ static ivk<T extends () => any>(fn: T): ReturnType<T>;
314
+ /**一个可供sort使用的从小到大排序的函数 */
315
+ static s2l(a: number, b: number): number;
316
+ /**一个可供sort使用的从大到小排序的函数 */
317
+ static l2s(a: number, b: number): number;
309
318
  }
310
319
  export {};
@@ -44,12 +44,12 @@ const UtilDecorators_1 = require("./UtilDecorators");
44
44
  const path_1 = __importDefault(require("path"));
45
45
  const UtilFileTools_1 = require("./UtilFileTools");
46
46
  const util_1 = require("util");
47
- const LiteFunction_1 = require("./LiteFunction");
48
47
  const HashMethodList = ["md5", "sha1", "sha256", "sha512", "sha3", "blake2", "blake3"];
49
48
  /**永不完成的Promise单例 */
50
49
  const NeverResolvedPromise = new Promise(() => { });
51
50
  /**常用函数 */
52
51
  class UtilFunc {
52
+ //#region 杂项
53
53
  /**获取当前时间戳
54
54
  * @returns 时间戳
55
55
  */
@@ -104,8 +104,8 @@ class UtilFunc {
104
104
  return crypto.createHash(method).update(str).digest('hex');
105
105
  }
106
106
  static async sleep(timeMs, result) {
107
- return new Promise(function (resolve, rejecte) {
108
- let timer = setTimeout(function () {
107
+ return new Promise((resolve, rejecte) => {
108
+ const timer = setTimeout(() => {
109
109
  resolve(result);
110
110
  }, timeMs);
111
111
  });
@@ -386,6 +386,150 @@ class UtilFunc {
386
386
  return JSON.stringify(token, compressReplacer, space)
387
387
  .replace(new RegExp(`"${ec}(.*?)${ec}"`, 'g'), (match, p1) => p1.replace(/\\([\\"])/g, '$1'));
388
388
  }
389
+ /**验证一个变量的类型是否为 T
390
+ * @template T - 验证类型
391
+ * @param t - 验证目标
392
+ */
393
+ static assertType(t) { return t; }
394
+ /**验证一个变量的类型是否为字面量
395
+ * 仅限浅层
396
+ * @template T - 验证类型
397
+ * @param t - 验证目标
398
+ */
399
+ static assertLiteral(t) { return t; }
400
+ /**深克隆 序列化并反序列化
401
+ * @template T - JToken类型的泛型
402
+ * @param obj - 克隆目标
403
+ * @returns 克隆结果
404
+ */
405
+ static deepClone(obj) {
406
+ return JSON.parse(JSON.stringify(obj));
407
+ }
408
+ /**是否为安全的数字
409
+ * 非NaN 非null/undefined
410
+ * 且是数字
411
+ * @param num - 所要检测的数字
412
+ * @returns 是否安全
413
+ */
414
+ static isSafeNumber(num) {
415
+ if (num == null)
416
+ return false;
417
+ if (typeof num === 'number') {
418
+ if (isNaN(num))
419
+ return false;
420
+ return true;
421
+ }
422
+ return false;
423
+ }
424
+ /**移除多行字符串中每行开始的最小空格数。
425
+ *
426
+ * @param input - 需要处理的多行 字符串模板 或 字符串。
427
+ * @param values - 插入模板字符串中的值。
428
+ * @returns 返回处理后的字符串,每行开始的空格数已被最小化。
429
+ *
430
+ * @example
431
+ * const name = 'World';
432
+ * const str = dedent`
433
+ * Hello,
434
+ * ${name}!
435
+ * `;
436
+ * console.log(str);
437
+ * // 输出:
438
+ * // Hello,
439
+ * // World!
440
+ */
441
+ static dedent(input, ...values) {
442
+ const str = typeof input === 'string'
443
+ ? input
444
+ : input.reduce((result, string, i) => result + string + (values[i] ?? ''), '');
445
+ const lines = str.split('\n');
446
+ const minIndent = Math.min(...lines.filter(line => line.trim() !== '').map(line => line.search(/\S/)));
447
+ return lines.map(line => line.slice(minIndent)).join('\n');
448
+ }
449
+ /**抛出错误
450
+ * @param message - 错误信息
451
+ * @param lvl - 日志等级
452
+ * @param opt - 额外参数
453
+ */
454
+ static throwError(message, lvl, opt) {
455
+ const e = new Error(message);
456
+ const stackLines = e.stack.split('\n');
457
+ e.stack = [stackLines[0]].concat(stackLines.slice(2)).join('\n'); // 移除第一行的堆栈信息
458
+ Object.assign(e, opt);
459
+ if (lvl) {
460
+ //SLogger.log(lvl,message);
461
+ UtilLogger_1.SLogger.log(lvl, e.stack);
462
+ }
463
+ throw e;
464
+ }
465
+ /**获取函数调用位置 getFunctionLocation
466
+ * @param stack - 深度 默认1, 即getFuncLoc函数被调用的位置
467
+ */
468
+ static getFuncLoc(stack = 1) {
469
+ const stackLines = new Error().stack.split('\n');
470
+ const regex = /([a-zA-Z]+?:.+?):(\d+?:\d+)/;
471
+ //console.log(stackLines)
472
+ const match = regex.exec(stackLines[stack + 1]);
473
+ if (match) {
474
+ const filePath = match[1];
475
+ const lineNumber = match[2];
476
+ return { filePath, lineNumber };
477
+ }
478
+ return undefined;
479
+ }
480
+ static publicIp;
481
+ /**获取当前公网ipv4 */
482
+ static async getPublicIpv4() {
483
+ if (UtilFunc.publicIp === undefined)
484
+ UtilFunc.publicIp = await UtilFunc.dynamicImport('public-ip');
485
+ return UtilFunc.publicIp.publicIpv4();
486
+ }
487
+ /**动态导入模块的函数。这个函数是为了在TypeScript的模块系统配置为CommonJS时,防止动态import被转译为require而设计的。
488
+ * 使用这个函数,你可以在TypeScript中动态地导入模块,而不需要担心import()被转译为require()。
489
+ * 请注意,这个函数使用了eval(),可能会带来安全风险。
490
+ *
491
+ * @param moduleName - 需要导入的模块的名称。
492
+ * @returns 返回一个Promise。当模块被成功导入时,这个Promise会解析为导入的模块。如果导入失败,这个Promise会被拒绝。
493
+ *
494
+ * @example
495
+ * async function main() {
496
+ * const pip = (await dynamicImport('public-ip')).default;
497
+ * console.log(await pip.v4());
498
+ * }
499
+ * main();
500
+ *
501
+ * @since Node.js 13.2,Node.js开始支持动态import。
502
+ */
503
+ static async dynamicImport(moduleName) {
504
+ return await eval(`import('${moduleName}')`);
505
+ }
506
+ /**缓存池 */
507
+ static cachePool = new WeakMap();
508
+ /**创建一个带有缓存有效期的memoize函数
509
+ * 只在传入值均为JToken时有效
510
+ * @param fn - 需要被memoize的函数
511
+ * @param expiry - 缓存的有效期 毫秒 默认为Infinity, 表示缓存永不过期。
512
+ * @returns 返回一个新的函数,这个函数在调用时会尝试从缓存中获取结果,如果缓存不存在或已过期,就会调用原函数并缓存其结果。
513
+ */
514
+ static memoize(fn, expiry = Infinity) {
515
+ const cache = UtilFunc.cachePool.get(fn) ?? UtilFunc.ivk(() => {
516
+ const c = new Map();
517
+ UtilFunc.cachePool.set(fn, c);
518
+ return c;
519
+ });
520
+ return ((...args) => {
521
+ const key = JSON.stringify(args);
522
+ const now = Date.now();
523
+ const cached = cache.get(key);
524
+ if (cached && now - cached.timestamp < expiry)
525
+ return cached.result;
526
+ const result = fn(...args);
527
+ cache.set(key, { result, timestamp: now });
528
+ return result;
529
+ });
530
+ }
531
+ //#endregion
532
+ //#region 队列处理
389
533
  /**代办表 用于队列处理等待 */
390
534
  static pendingMap = {};
391
535
  /**队列处理
@@ -448,6 +592,8 @@ class UtilFunc {
448
592
  const pd = UtilFunc.pendingMap[flag];
449
593
  return pd != null ? pd.length : 0;
450
594
  }
595
+ //#endregion
596
+ //#region symbol化处理工具
451
597
  /**创建一个Outcome */
452
598
  static outcome(key, value) {
453
599
  return {
@@ -545,104 +691,8 @@ class UtilFunc {
545
691
  UtilFunc.throwError(errLog ?? "expect验证了一个None值", "error");
546
692
  return t;
547
693
  }
548
- /**验证一个变量的类型是否为 T
549
- * @template T - 验证类型
550
- * @param t - 验证目标
551
- */
552
- static assertType(t) { return t; }
553
- /**验证一个变量的类型是否为字面量
554
- * 仅限浅层
555
- * @template T - 验证类型
556
- * @param t - 验证目标
557
- */
558
- static assertLiteral(t) { return t; }
559
- /**深克隆 序列化并反序列化
560
- * @template T - JToken类型的泛型
561
- * @param obj - 克隆目标
562
- * @returns 克隆结果
563
- */
564
- static deepClone(obj) {
565
- return JSON.parse(JSON.stringify(obj));
566
- }
567
- /**是否为安全的数字
568
- * 非NaN 非null/undefined
569
- * 且是数字
570
- * @param num - 所要检测的数字
571
- * @returns 是否安全
572
- */
573
- static isSafeNumber(num) {
574
- if (num == null)
575
- return false;
576
- if (typeof num === 'number') {
577
- if (isNaN(num))
578
- return false;
579
- return true;
580
- }
581
- return false;
582
- }
583
- /**移除多行字符串中每行开始的最小空格数。
584
- *
585
- * @param input - 需要处理的多行 字符串模板 或 字符串。
586
- * @param values - 插入模板字符串中的值。
587
- * @returns 返回处理后的字符串,每行开始的空格数已被最小化。
588
- *
589
- * @example
590
- * const name = 'World';
591
- * const str = dedent`
592
- * Hello,
593
- * ${name}!
594
- * `;
595
- * console.log(str);
596
- * // 输出:
597
- * // Hello,
598
- * // World!
599
- */
600
- static dedent(input, ...values) {
601
- const str = typeof input === 'string'
602
- ? input
603
- : input.reduce((result, string, i) => result + string + (values[i] ?? ''), '');
604
- const lines = str.split('\n');
605
- const minIndent = Math.min(...lines.filter(line => line.trim() !== '').map(line => line.search(/\S/)));
606
- return lines.map(line => line.slice(minIndent)).join('\n');
607
- }
608
- /**抛出错误
609
- * @param message - 错误信息
610
- * @param lvl - 日志等级
611
- * @param opt - 额外参数
612
- */
613
- static throwError(message, lvl, opt) {
614
- const e = new Error(message);
615
- const stackLines = e.stack.split('\n');
616
- e.stack = [stackLines[0]].concat(stackLines.slice(2)).join('\n'); // 移除第一行的堆栈信息
617
- Object.assign(e, opt);
618
- if (lvl) {
619
- //SLogger.log(lvl,message);
620
- UtilLogger_1.SLogger.log(lvl, e.stack);
621
- }
622
- throw e;
623
- }
624
- /**获取函数调用位置 getFunctionLocation
625
- * @param stack - 深度 默认1, 即getFuncLoc函数被调用的位置
626
- */
627
- static getFuncLoc(stack = 1) {
628
- const stackLines = new Error().stack.split('\n');
629
- const regex = /([a-zA-Z]+?:.+?):(\d+?:\d+)/;
630
- //console.log(stackLines)
631
- const match = regex.exec(stackLines[stack + 1]);
632
- if (match) {
633
- const filePath = match[1];
634
- const lineNumber = match[2];
635
- return { filePath, lineNumber };
636
- }
637
- return undefined;
638
- }
639
- static publicIp;
640
- /**获取当前公网ipv4 */
641
- static async getPublicIpv4() {
642
- if (UtilFunc.publicIp === undefined)
643
- UtilFunc.publicIp = await UtilFunc.dynamicImport('public-ip');
644
- return UtilFunc.publicIp.publicIpv4();
645
- }
694
+ //#endregion
695
+ //#region 显式处理错误工具
646
696
  /**将传入函数包装为显式处理错误的函数
647
697
  * @param func - 待转换函数
648
698
  * @returns 转换完成的函数
@@ -677,50 +727,8 @@ class UtilFunc {
677
727
  }
678
728
  };
679
729
  }
680
- /**动态导入模块的函数。这个函数是为了在TypeScript的模块系统配置为CommonJS时,防止动态import被转译为require而设计的。
681
- * 使用这个函数,你可以在TypeScript中动态地导入模块,而不需要担心import()被转译为require()。
682
- * 请注意,这个函数使用了eval(),可能会带来安全风险。
683
- *
684
- * @param moduleName - 需要导入的模块的名称。
685
- * @returns 返回一个Promise。当模块被成功导入时,这个Promise会解析为导入的模块。如果导入失败,这个Promise会被拒绝。
686
- *
687
- * @example
688
- * async function main() {
689
- * const pip = (await dynamicImport('public-ip')).default;
690
- * console.log(await pip.v4());
691
- * }
692
- * main();
693
- *
694
- * @since Node.js 13.2,Node.js开始支持动态import。
695
- */
696
- static async dynamicImport(moduleName) {
697
- return await eval(`import('${moduleName}')`);
698
- }
699
- /**缓存池 */
700
- static cachePool = new WeakMap();
701
- /**创建一个带有缓存有效期的memoize函数
702
- * 只在传入值均为JToken时有效
703
- * @param fn - 需要被memoize的函数
704
- * @param expiry - 缓存的有效期 毫秒 默认为Infinity, 表示缓存永不过期。
705
- * @returns 返回一个新的函数,这个函数在调用时会尝试从缓存中获取结果,如果缓存不存在或已过期,就会调用原函数并缓存其结果。
706
- */
707
- static memoize(fn, expiry = Infinity) {
708
- const cache = UtilFunc.cachePool.get(fn) ?? (0, LiteFunction_1.ivk)(() => {
709
- const c = new Map();
710
- UtilFunc.cachePool.set(fn, c);
711
- return c;
712
- });
713
- return ((...args) => {
714
- const key = JSON.stringify(args);
715
- const now = Date.now();
716
- const cached = cache.get(key);
717
- if (cached && now - cached.timestamp < expiry)
718
- return cached.result;
719
- const result = fn(...args);
720
- cache.set(key, { result, timestamp: now });
721
- return result;
722
- });
723
- }
730
+ //#endregion
731
+ //#region 解析srt
724
732
  /**将hh:mm:ss,ms格式转换为毫秒 */
725
733
  static parseSrtTime(time) {
726
734
  const [hours, minutes, seconds] = time.split(':');
@@ -764,6 +772,23 @@ class UtilFunc {
764
772
  return `${index + 1}\n${UtilFunc.formatSrtTime(segment.start)} --> ${UtilFunc.formatSrtTime(segment.end)}\n${segment.text}\n`;
765
773
  }).join('\n');
766
774
  }
775
+ //#endregion
776
+ //#region 常用直传的快速调用函数
777
+ /**立即执行传入的函数
778
+ * @param fn - 需要立即执行的函数。
779
+ * @returns 返回 fn 函数的执行结果。
780
+ */
781
+ static ivk(fn) {
782
+ return fn();
783
+ }
784
+ /**一个可供sort使用的从小到大排序的函数 */
785
+ static s2l(a, b) {
786
+ return a - b;
787
+ }
788
+ /**一个可供sort使用的从大到小排序的函数 */
789
+ static l2s(a, b) {
790
+ return b - a;
791
+ }
767
792
  }
768
793
  exports.UtilFunc = UtilFunc;
769
794
  __decorate([
package/dist/index.d.ts CHANGED
@@ -9,6 +9,5 @@ export * from './UtilDecorators';
9
9
  export * from './UtilFileTools';
10
10
  export * from './UtilLogger';
11
11
  export * from './UtilFP';
12
- export * from './QuickFunction';
12
+ export * from './QuickExport';
13
13
  export * from './UtilI18n';
14
- export * from './LiteFunction';
package/dist/index.js CHANGED
@@ -25,6 +25,5 @@ __exportStar(require("./UtilDecorators"), exports);
25
25
  __exportStar(require("./UtilFileTools"), exports);
26
26
  __exportStar(require("./UtilLogger"), exports);
27
27
  __exportStar(require("./UtilFP"), exports);
28
- __exportStar(require("./QuickFunction"), exports);
28
+ __exportStar(require("./QuickExport"), exports);
29
29
  __exportStar(require("./UtilI18n"), exports);
30
- __exportStar(require("./LiteFunction"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zwa73/utils",
3
- "version": "1.0.193",
3
+ "version": "1.0.194",
4
4
  "description": "my utils",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -24,6 +24,7 @@ export const {
24
24
  eitherize,
25
25
  taskEitherize,
26
26
  memoize,
27
+ ivk,l2s,s2l,
27
28
  } = UtilFunc;
28
29
 
29
30
  export const {
package/src/UtilClass.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { matchProc } from "./QuickFunction";
1
+ import { matchProc } from "./QuickExport";
2
2
  import { Keyable, Literal } from "./UtilInterfaces";
3
3
  import Handlebars from 'handlebars';
4
4
  import { SLogger } from "./UtilLogger";
package/src/UtilFP.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { isFailed, likeNone } from "./QuickFunction";
1
+ import { isFailed, likeNone } from "./QuickExport";
2
2
  import { AnyRecord, Keyable, Literal, Matchable, MatchableFlag, ProperSubset, ProperSubsetCheck } from "./UtilInterfaces";
3
3
  import { Failed, FailedLike, None } from "./UtilSymbol";
4
4
 
@@ -4,7 +4,7 @@ import path from "pathe";
4
4
  import * as fs from "fs";
5
5
  import { SLogger } from "@/src/UtilLogger";
6
6
  import { Stream } from "./UtilClass";
7
- import { throwError } from "./QuickFunction";
7
+ import { throwError } from "./QuickExport";
8
8
 
9
9
  /**输入输出路径映射
10
10
  * 输入路径:输入路径
@@ -8,7 +8,6 @@ import opath from 'path';
8
8
  import { UtilFT } from "./UtilFileTools";
9
9
  import {inspect} from 'util';
10
10
  import type * as publicIp from 'public-ip';
11
- import { ivk } from "./LiteFunction";
12
11
 
13
12
  const HashMethodList = ["md5","sha1","sha256","sha512","sha3","blake2","blake3"] as const;
14
13
  type HashMethod = typeof HashMethodList[number];
@@ -74,6 +73,8 @@ type EachFieldCallback = (key: string, value: JToken,parent: JObject) => void;
74
73
 
75
74
  /**常用函数 */
76
75
  export class UtilFunc{
76
+
77
+ //#region 杂项
77
78
  /**获取当前时间戳
78
79
  * @returns 时间戳
79
80
  */
@@ -134,7 +135,6 @@ static calcHash(str:string,method:HashMethod='md5') {
134
135
  return crypto.createHash(method).update(str).digest('hex');
135
136
  }
136
137
 
137
-
138
138
  /**等待 timeMs 毫秒
139
139
  * @async
140
140
  * @param timeMs - 等待的毫秒数
@@ -149,8 +149,8 @@ static async sleep<T>(timeMs: number): Promise<void>
149
149
  */
150
150
  static async sleep<T>(timeMs: number, result:T): Promise<T>
151
151
  static async sleep<T>(timeMs: number, result?:T): Promise<T|undefined> {
152
- return new Promise(function (resolve, rejecte) {
153
- let timer = setTimeout(function () {
152
+ return new Promise((resolve, rejecte) => {
153
+ const timer = setTimeout(() => {
154
154
  resolve(result);
155
155
  }, timeMs);
156
156
  });
@@ -457,6 +457,167 @@ static stringifyJToken(token:JToken|IJData,opt?:StringifyOpt){
457
457
  p1.replace(/\\([\\"])/g, '$1'));
458
458
  }
459
459
 
460
+ /**验证一个变量的类型是否为 T
461
+ * @template T - 验证类型
462
+ * @param t - 验证目标
463
+ */
464
+ static assertType<T>(t:T):T{return t;}
465
+
466
+ /**验证一个变量的类型是否为字面量
467
+ * 仅限浅层
468
+ * @template T - 验证类型
469
+ * @param t - 验证目标
470
+ */
471
+ static assertLiteral<T>(t:Literal<T>):T{return t as T;}
472
+
473
+ /**深克隆 序列化并反序列化
474
+ * @template T - JToken类型的泛型
475
+ * @param obj - 克隆目标
476
+ * @returns 克隆结果
477
+ */
478
+ static deepClone<T extends JToken>(obj: T): T {
479
+ return JSON.parse(JSON.stringify(obj));
480
+ }
481
+
482
+ /**是否为安全的数字
483
+ * 非NaN 非null/undefined
484
+ * 且是数字
485
+ * @param num - 所要检测的数字
486
+ * @returns 是否安全
487
+ */
488
+ static isSafeNumber(num: unknown): boolean {
489
+ if (num == null) return false;
490
+ if(typeof num === 'number') {
491
+ if(isNaN(num)) return false;
492
+ return true;
493
+ }
494
+ return false;
495
+ }
496
+
497
+ /**移除多行字符串中每行开始的最小空格数。
498
+ *
499
+ * @param input - 需要处理的多行 字符串模板 或 字符串。
500
+ * @param values - 插入模板字符串中的值。
501
+ * @returns 返回处理后的字符串,每行开始的空格数已被最小化。
502
+ *
503
+ * @example
504
+ * const name = 'World';
505
+ * const str = dedent`
506
+ * Hello,
507
+ * ${name}!
508
+ * `;
509
+ * console.log(str);
510
+ * // 输出:
511
+ * // Hello,
512
+ * // World!
513
+ */
514
+ static dedent(input: TemplateStringsArray|string, ...values: any[]): string {
515
+ const str = typeof input === 'string'
516
+ ? input
517
+ : input.reduce((result, string, i) => result + string + (values[i] ?? ''), '');
518
+ const lines = str.split('\n');
519
+ const minIndent = Math.min(
520
+ ...lines.filter(line => line.trim() !== '').map(line => line.search(/\S/))
521
+ );
522
+ return lines.map(line => line.slice(minIndent)).join('\n');
523
+ }
524
+
525
+ /**抛出错误
526
+ * @param message - 错误信息
527
+ * @param lvl - 日志等级
528
+ * @param opt - 额外参数
529
+ */
530
+ static throwError(message:string,lvl?:LogLevel,opt?:{}):never{
531
+ const e = new Error(message);
532
+ const stackLines = e.stack!.split('\n');
533
+ e.stack = [stackLines[0]].concat(stackLines.slice(2)).join('\n'); // 移除第一行的堆栈信息
534
+ Object.assign(e, opt);
535
+ if(lvl){
536
+ //SLogger.log(lvl,message);
537
+ SLogger.log(lvl,e.stack);
538
+ }
539
+ throw e;
540
+ }
541
+
542
+ /**获取函数调用位置 getFunctionLocation
543
+ * @param stack - 深度 默认1, 即getFuncLoc函数被调用的位置
544
+ */
545
+ static getFuncLoc(stack=1) {
546
+ const stackLines = new Error().stack!.split('\n');
547
+ const regex = /([a-zA-Z]+?:.+?):(\d+?:\d+)/;
548
+ //console.log(stackLines)
549
+ const match = regex.exec(stackLines[stack+1]);
550
+ if(match){
551
+ const filePath = match[1];
552
+ const lineNumber = match[2] as `${number}:${number}`;
553
+ return {filePath,lineNumber}
554
+ }
555
+ return undefined;
556
+ }
557
+
558
+ private static publicIp?:typeof publicIp;
559
+ /**获取当前公网ipv4 */
560
+ static async getPublicIpv4(){
561
+ if(UtilFunc.publicIp===undefined)
562
+ UtilFunc.publicIp = await UtilFunc.dynamicImport('public-ip') as typeof publicIp;
563
+ return UtilFunc.publicIp.publicIpv4();
564
+ }
565
+
566
+ /**动态导入模块的函数。这个函数是为了在TypeScript的模块系统配置为CommonJS时,防止动态import被转译为require而设计的。
567
+ * 使用这个函数,你可以在TypeScript中动态地导入模块,而不需要担心import()被转译为require()。
568
+ * 请注意,这个函数使用了eval(),可能会带来安全风险。
569
+ *
570
+ * @param moduleName - 需要导入的模块的名称。
571
+ * @returns 返回一个Promise。当模块被成功导入时,这个Promise会解析为导入的模块。如果导入失败,这个Promise会被拒绝。
572
+ *
573
+ * @example
574
+ * async function main() {
575
+ * const pip = (await dynamicImport('public-ip')).default;
576
+ * console.log(await pip.v4());
577
+ * }
578
+ * main();
579
+ *
580
+ * @since Node.js 13.2,Node.js开始支持动态import。
581
+ */
582
+ static async dynamicImport(moduleName:string):Promise<any> {
583
+ return await eval(`import('${moduleName}')`);
584
+ }
585
+
586
+ /**缓存池 */
587
+ static cachePool = new WeakMap<Function, Map<string, { result: any, timestamp: number }>>();
588
+
589
+ /**创建一个带有缓存有效期的memoize函数
590
+ * 只在传入值均为JToken时有效
591
+ * @param fn - 需要被memoize的函数
592
+ * @param expiry - 缓存的有效期 毫秒 默认为Infinity, 表示缓存永不过期。
593
+ * @returns 返回一个新的函数,这个函数在调用时会尝试从缓存中获取结果,如果缓存不存在或已过期,就会调用原函数并缓存其结果。
594
+ */
595
+ static memoize<T extends (...args:any[])=>any> (fn: T, expiry = Infinity):
596
+ T extends (...args:infer In)=>any
597
+ ? AllExtends<In,JToken> extends true ? T : never
598
+ : never {
599
+ const cache = UtilFunc.cachePool.get(fn) ?? UtilFunc.ivk(()=>{
600
+ const c = new Map();
601
+ UtilFunc.cachePool.set(fn, c);
602
+ return c;
603
+ });
604
+
605
+ return ((...args: Parameters<T>): ReturnType<T> => {
606
+ const key = JSON.stringify(args);
607
+ const now = Date.now();
608
+ const cached = cache.get(key);
609
+
610
+ if (cached && now - cached.timestamp < expiry)
611
+ return cached.result;
612
+
613
+ const result = fn(...args);
614
+ cache.set(key, { result, timestamp: now });
615
+ return result;
616
+ }) as any;
617
+ }
618
+ //#endregion
619
+
620
+ //#region 队列处理
460
621
  /**代办表 用于队列处理等待 */
461
622
  static pendingMap:Record<Keyable,AnyFunc[]> = {};
462
623
 
@@ -512,6 +673,7 @@ static queueProc<T>(flag: Keyable, task: () => Promise<T>): Promise<T> {
512
673
  // 返回Promise,以便调用者可以等待任务完成
513
674
  return promise;
514
675
  }
676
+
515
677
  /**队列获取目标的代办事件数
516
678
  * @param flag - 队列标签
517
679
  */
@@ -519,9 +681,9 @@ static queueLength(flag:Keyable){
519
681
  const pd = UtilFunc.pendingMap[flag]
520
682
  return pd!=null ? pd.length : 0;
521
683
  }
684
+ //#endregion
522
685
 
523
-
524
-
686
+ //#region symbol化处理工具
525
687
  /**创建一个Outcome */
526
688
  static outcome<K extends Keyable,V> (key:K,value:V):Outcome<K,V>{
527
689
  return {
@@ -530,7 +692,6 @@ static outcome<K extends Keyable,V> (key:K,value:V):Outcome<K,V>{
530
692
  }
531
693
  }
532
694
 
533
-
534
695
  /**处理联合值
535
696
  * @param t - 目标值
536
697
  * @param procObj - 所有可能的id组成的处理函数映射 (status, result)=>any
@@ -582,8 +743,6 @@ static matchPartialProc<
582
743
  return undefined;
583
744
  }
584
745
 
585
-
586
-
587
746
  /**根据典型的成功或失败状态运行函数
588
747
  * @param t - 目标值
589
748
  * @param sucessFunc - 成功则运行的函数 (result)=>any
@@ -606,6 +765,7 @@ static sucesProc<T extends Matchable<StatusSymbol>,
606
765
  if(t!==None) SLogger.warn(`sucesProc 传入了一个不匹配的值, 将作为None运行: `,t);
607
766
  return noneFunc() as any;
608
767
  }
768
+
609
769
  /**是失败的 */
610
770
  static isFailed<T>
611
771
  (tg:T):'E' extends ProperSubsetCheck<symbol,T>? boolean
@@ -655,113 +815,9 @@ static expect<T>(t:T,errLog?:string):Exclude<T,None>{
655
815
  if(t===None) UtilFunc.throwError(errLog??"expect验证了一个None值","error");
656
816
  return t as Exclude<T,None>;
657
817
  }
818
+ //#endregion
658
819
 
659
- /**验证一个变量的类型是否为 T
660
- * @template T - 验证类型
661
- * @param t - 验证目标
662
- */
663
- static assertType<T>(t:T):T{return t;}
664
- /**验证一个变量的类型是否为字面量
665
- * 仅限浅层
666
- * @template T - 验证类型
667
- * @param t - 验证目标
668
- */
669
- static assertLiteral<T>(t:Literal<T>):T{return t as T;}
670
-
671
- /**深克隆 序列化并反序列化
672
- * @template T - JToken类型的泛型
673
- * @param obj - 克隆目标
674
- * @returns 克隆结果
675
- */
676
- static deepClone<T extends JToken>(obj: T): T {
677
- return JSON.parse(JSON.stringify(obj));
678
- }
679
-
680
- /**是否为安全的数字
681
- * 非NaN 非null/undefined
682
- * 且是数字
683
- * @param num - 所要检测的数字
684
- * @returns 是否安全
685
- */
686
- static isSafeNumber(num: unknown): boolean {
687
- if (num == null) return false;
688
- if(typeof num === 'number') {
689
- if(isNaN(num)) return false;
690
- return true;
691
- }
692
- return false;
693
- }
694
-
695
- /**移除多行字符串中每行开始的最小空格数。
696
- *
697
- * @param input - 需要处理的多行 字符串模板 或 字符串。
698
- * @param values - 插入模板字符串中的值。
699
- * @returns 返回处理后的字符串,每行开始的空格数已被最小化。
700
- *
701
- * @example
702
- * const name = 'World';
703
- * const str = dedent`
704
- * Hello,
705
- * ${name}!
706
- * `;
707
- * console.log(str);
708
- * // 输出:
709
- * // Hello,
710
- * // World!
711
- */
712
- static dedent(input: TemplateStringsArray|string, ...values: any[]): string {
713
- const str = typeof input === 'string'
714
- ? input
715
- : input.reduce((result, string, i) => result + string + (values[i] ?? ''), '');
716
- const lines = str.split('\n');
717
- const minIndent = Math.min(
718
- ...lines.filter(line => line.trim() !== '').map(line => line.search(/\S/))
719
- );
720
- return lines.map(line => line.slice(minIndent)).join('\n');
721
- }
722
- /**抛出错误
723
- * @param message - 错误信息
724
- * @param lvl - 日志等级
725
- * @param opt - 额外参数
726
- */
727
- static throwError(message:string,lvl?:LogLevel,opt?:{}):never{
728
- const e = new Error(message);
729
- const stackLines = e.stack!.split('\n');
730
- e.stack = [stackLines[0]].concat(stackLines.slice(2)).join('\n'); // 移除第一行的堆栈信息
731
- Object.assign(e, opt);
732
- if(lvl){
733
- //SLogger.log(lvl,message);
734
- SLogger.log(lvl,e.stack);
735
- }
736
- throw e;
737
- }
738
-
739
- /**获取函数调用位置 getFunctionLocation
740
- * @param stack - 深度 默认1, 即getFuncLoc函数被调用的位置
741
- */
742
- static getFuncLoc(stack=1) {
743
- const stackLines = new Error().stack!.split('\n');
744
- const regex = /([a-zA-Z]+?:.+?):(\d+?:\d+)/;
745
- //console.log(stackLines)
746
- const match = regex.exec(stackLines[stack+1]);
747
- if(match){
748
- const filePath = match[1];
749
- const lineNumber = match[2] as `${number}:${number}`;
750
- return {filePath,lineNumber}
751
- }
752
- return undefined;
753
- }
754
-
755
-
756
- private static publicIp?:typeof publicIp;
757
-
758
- /**获取当前公网ipv4 */
759
- static async getPublicIpv4(){
760
- if(UtilFunc.publicIp===undefined)
761
- UtilFunc.publicIp = await UtilFunc.dynamicImport('public-ip') as typeof publicIp;
762
- return UtilFunc.publicIp.publicIpv4();
763
- }
764
-
820
+ //#region 显式处理错误工具
765
821
  /**将传入函数包装为显式处理错误的函数
766
822
  * @param func - 待转换函数
767
823
  * @returns 转换完成的函数
@@ -794,62 +850,9 @@ static taskEitherize<T extends (...args:any)=>Promise<any>>(func:T) {
794
850
  }
795
851
  };
796
852
  }
853
+ //#endregion
797
854
 
798
- /**动态导入模块的函数。这个函数是为了在TypeScript的模块系统配置为CommonJS时,防止动态import被转译为require而设计的。
799
- * 使用这个函数,你可以在TypeScript中动态地导入模块,而不需要担心import()被转译为require()。
800
- * 请注意,这个函数使用了eval(),可能会带来安全风险。
801
- *
802
- * @param moduleName - 需要导入的模块的名称。
803
- * @returns 返回一个Promise。当模块被成功导入时,这个Promise会解析为导入的模块。如果导入失败,这个Promise会被拒绝。
804
- *
805
- * @example
806
- * async function main() {
807
- * const pip = (await dynamicImport('public-ip')).default;
808
- * console.log(await pip.v4());
809
- * }
810
- * main();
811
- *
812
- * @since Node.js 13.2,Node.js开始支持动态import。
813
- */
814
- static async dynamicImport(moduleName:string):Promise<any> {
815
- return await eval(`import('${moduleName}')`);
816
- }
817
-
818
- /**缓存池 */
819
- static cachePool = new WeakMap<Function, Map<string, { result: any, timestamp: number }>>();
820
-
821
- /**创建一个带有缓存有效期的memoize函数
822
- * 只在传入值均为JToken时有效
823
- * @param fn - 需要被memoize的函数
824
- * @param expiry - 缓存的有效期 毫秒 默认为Infinity, 表示缓存永不过期。
825
- * @returns 返回一个新的函数,这个函数在调用时会尝试从缓存中获取结果,如果缓存不存在或已过期,就会调用原函数并缓存其结果。
826
- */
827
- static memoize<T extends (...args:any[])=>any> (fn: T, expiry = Infinity):
828
- T extends (...args:infer In)=>any
829
- ? AllExtends<In,JToken> extends true ? T : never
830
- : never {
831
- const cache = UtilFunc.cachePool.get(fn) ?? ivk(()=>{
832
- const c = new Map();
833
- UtilFunc.cachePool.set(fn, c);
834
- return c;
835
- });
836
-
837
- return ((...args: Parameters<T>): ReturnType<T> => {
838
- const key = JSON.stringify(args);
839
- const now = Date.now();
840
- const cached = cache.get(key);
841
-
842
- if (cached && now - cached.timestamp < expiry)
843
- return cached.result;
844
-
845
- const result = fn(...args);
846
- cache.set(key, { result, timestamp: now });
847
- return result;
848
- }) as any;
849
- }
850
-
851
-
852
-
855
+ //#region 解析srt
853
856
  /**将hh:mm:ss,ms格式转换为毫秒 */
854
857
  static parseSrtTime(time: string): number {
855
858
  const [hours, minutes, seconds] = time.split(':');
@@ -899,5 +902,24 @@ static createSrt(segments: SrtSegment[]): string {
899
902
  return `${index + 1}\n${UtilFunc.formatSrtTime(segment.start)} --> ${UtilFunc.formatSrtTime(segment.end)}\n${segment.text}\n`;
900
903
  }).join('\n');
901
904
  }
905
+ //#endregion
906
+
907
+ //#region 常用直传的快速调用函数
908
+ /**立即执行传入的函数
909
+ * @param fn - 需要立即执行的函数。
910
+ * @returns 返回 fn 函数的执行结果。
911
+ */
912
+ static ivk<T extends ()=>any>(fn:T): ReturnType<T> {
913
+ return fn();
914
+ }
915
+ /**一个可供sort使用的从小到大排序的函数 */
916
+ static s2l(a:number,b:number) {
917
+ return a-b;
918
+ }
919
+ /**一个可供sort使用的从大到小排序的函数 */
920
+ static l2s(a:number,b:number) {
921
+ return b-a;
922
+ }
923
+ //#endregion
902
924
 
903
925
  }
package/src/index.ts CHANGED
@@ -9,6 +9,5 @@ export * from './UtilDecorators';
9
9
  export * from './UtilFileTools';
10
10
  export * from './UtilLogger';
11
11
  export * from './UtilFP';
12
- export * from './QuickFunction';
13
- export * from './UtilI18n';
14
- export * from './LiteFunction';
12
+ export * from './QuickExport';
13
+ export * from './UtilI18n';
@@ -1,9 +0,0 @@
1
- /**立即执行传入的函数
2
- * @param fn - 需要立即执行的函数。
3
- * @returns 返回 fn 函数的执行结果。
4
- */
5
- export declare function ivk<T extends () => any>(fn: T): ReturnType<T>;
6
- /**一个可供sort使用的从小到大排序的函数 */
7
- export declare function s2l(a: number, b: number): number;
8
- /**一个可供sort使用的从大到小排序的函数 */
9
- export declare function l2s(a: number, b: number): number;
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ivk = ivk;
4
- exports.s2l = s2l;
5
- exports.l2s = l2s;
6
- /**立即执行传入的函数
7
- * @param fn - 需要立即执行的函数。
8
- * @returns 返回 fn 函数的执行结果。
9
- */
10
- function ivk(fn) {
11
- return fn();
12
- }
13
- /**一个可供sort使用的从小到大排序的函数 */
14
- function s2l(a, b) {
15
- return a - b;
16
- }
17
- /**一个可供sort使用的从大到小排序的函数 */
18
- function l2s(a, b) {
19
- return b - a;
20
- }
@@ -1,18 +0,0 @@
1
-
2
-
3
-
4
- /**立即执行传入的函数
5
- * @param fn - 需要立即执行的函数。
6
- * @returns 返回 fn 函数的执行结果。
7
- */
8
- export function ivk<T extends ()=>any>(fn:T): ReturnType<T> {
9
- return fn();
10
- }
11
- /**一个可供sort使用的从小到大排序的函数 */
12
- export function s2l(a:number,b:number) {
13
- return a-b;
14
- }
15
- /**一个可供sort使用的从大到小排序的函数 */
16
- export function l2s(a:number,b:number) {
17
- return b-a;
18
- }