From 374889ad076a3d120af87a85236d534efb79dfc2 Mon Sep 17 00:00:00 2001 From: CounterFire2023 <136581895+CounterFire2023@users.noreply.github.com> Date: Fri, 19 Jan 2024 15:37:00 +0800 Subject: [PATCH] update some comment --- README.md | 19 +++++++++++++++++++ src/common/AsyncQueue.ts | 22 --------------------- src/decorators/router.ts | 4 ++-- src/decorators/singleton.ts | 8 ++++---- src/utils/chain.util.ts | 6 +++--- src/utils/curry.util.ts | 10 +++++----- src/utils/date.util.ts | 38 ++++++++++++++++++------------------- src/utils/net.util.ts | 24 +++++++++-------------- src/utils/number.util.ts | 10 +++++----- src/utils/promise.util.ts | 8 ++++---- src/utils/security.util.ts | 16 ++++++++-------- src/utils/string.util.ts | 20 +++++++++---------- 12 files changed, 88 insertions(+), 97 deletions(-) diff --git a/README.md b/README.md index e69de29..0a61ce4 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,19 @@ +# ZUTILS + +Integrates some commonly used utility classes for convenient development. + +## 1. Usage + +***Important:: TypeScript version must be higher than 4.7!!*** +```bash +git submodule add --force git@git.kingsome.cn:zhanghongliang/zutils.git ./packages/zutils +yarn add file:packages/zutils +# or +yarn add link:packages/zutils +``` + +```typescript +import { SyncLocker, ZRedisClient } from 'zutils' +import { isTrue } from 'zutils/utils/string.util' + +``` \ No newline at end of file diff --git a/src/common/AsyncQueue.ts b/src/common/AsyncQueue.ts index 792c27e..d81d8ae 100644 --- a/src/common/AsyncQueue.ts +++ b/src/common/AsyncQueue.ts @@ -83,25 +83,3 @@ class DeferredPromise { }) } } - -// function main() { -// const queue = createAsyncQueue() -// queue.push(async () => { -// console.log(0) -// }) // returns 0 -// queue.push(async () => { -// console.log(1) - -// return new Promise((resolve, reject) => { -// setTimeout(() => { -// console.log('12') -// resolve() -// }, 1000) -// }) -// }) // returns 3 -// queue.push(async () => console.log(2)) // returns 3 -// queue.push(async () => console.log(3)) // returns 3 -// console.log('hi') -// } - -// main() diff --git a/src/decorators/router.ts b/src/decorators/router.ts index 2dbccf2..d1dafca 100644 --- a/src/decorators/router.ts +++ b/src/decorators/router.ts @@ -28,7 +28,7 @@ export function router(route?: string) { } const split = route.split(' ') if (split.length > 2) { - throw new Error('路由中只允许一个空格') + throw new Error('Only one space is allowed in @router()') } const [method, path] = split // @ts-ignore @@ -114,7 +114,7 @@ export function permission(permissions?: string | string[]) { } /** - * 有dept修饰器的, 需要验证部门id是否存在 + * If there is a dept modifier, you need to verify whether the department id exists. */ export function dept(depts?: string | string[]) { return (target: BaseController, name: string, value: PropertyDescriptor) => { diff --git a/src/decorators/singleton.ts b/src/decorators/singleton.ts index c43327d..7243bf8 100644 --- a/src/decorators/singleton.ts +++ b/src/decorators/singleton.ts @@ -1,12 +1,12 @@ /** - * 单例化一个class - * 使用方法: + * Singletonize a class + * Usage: * @singleton * class Test {} * new Test() === new Test() // returns `true` - * 也可以不使用 decorator + * It can also be used without a decorator * const TestSingleton = singleton(Test) - * new TestSingleton() === new TestSingleton() //returns 'true' + * new TestSingleton() === new TestSingleton() // returns `true` */ export const SINGLETON_KEY = Symbol() diff --git a/src/utils/chain.util.ts b/src/utils/chain.util.ts index 52a44a9..9edb5a2 100644 --- a/src/utils/chain.util.ts +++ b/src/utils/chain.util.ts @@ -80,8 +80,8 @@ export const sign = async ({ /** * convert address to EIP55 format * doc: https://eips.ethereum.org/EIPS/eip-55 - * @param address - * @returns + * @param address + * @returns */ export function toEIP55(address: string) { const lowerAddress = `${address}`.toLowerCase().replace('0x', '') @@ -137,4 +137,4 @@ export const decodeEvent = (abi: AbiItem, eventData: { data: string; topics: str } } return decodedData -} \ No newline at end of file +} diff --git a/src/utils/curry.util.ts b/src/utils/curry.util.ts index 548f149..14823d8 100644 --- a/src/utils/curry.util.ts +++ b/src/utils/curry.util.ts @@ -1,16 +1,16 @@ /** - * 柯里化一个函数 + * Currying a function * @param func * @returns */ export function curry(func: (...args0: any[]) => any) { return function curried(this: unknown, ...args: any[]) { if (args.length >= func.length) { - return func.apply(this, args); + return func.apply(this, args) } else { return function (this: unknown, ...args2: any[]) { - return curried.apply(this, args.concat(args2)); - }; + return curried.apply(this, args.concat(args2)) + } } - }; + } } diff --git a/src/utils/date.util.ts b/src/utils/date.util.ts index 3eee3a2..b2cf953 100644 --- a/src/utils/date.util.ts +++ b/src/utils/date.util.ts @@ -73,7 +73,7 @@ export function calcBetweenDays(time1: number, time2: number) { } /** - * 判断是否是今天 + * check if the time is today * @param {number} time * @return {boolean} */ @@ -106,42 +106,42 @@ export function getThisWeekData(): { startDay: string; endDay: string } { } /** - * 获取前后n周的周一和周日的日期 - * @param {number} n 0为当前周, 1为下一周, -1为上周 + * Get the start and end dates of the Monday and Sunday of the previous or next n weeks. + * @param {number} n 0 for the current week, 1 for the next week, -1 for the previous week * @return {{startDay: string, endDay: string}} */ export function weekData(n: number): { startDay: string; endDay: string } { const weekData = { startDay: '', endDay: '' } const date = new Date() - // 上周一的日期 + date.setDate(date.getDate() + 7 * n - date.getDay() + 1) weekData.startDay = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() - // 上周日的日期 date.setDate(date.getDate() + 6) weekData.endDay = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() return weekData } /** - * 将秒格式化成 hh:mm:ss的字符串 - * @param {number} sec - * @param {boolean} showSeconds 是否显示秒 - */ + * Format seconds into a string in the format hh:mm:ss + * @param {number} sec + * @param {boolean} showSeconds Whether to display seconds + */ export const second2str = (sec: number, showSeconds: boolean) => { - showSeconds = typeof showSeconds !== 'undefined' ? showSeconds : true; + showSeconds = typeof showSeconds !== 'undefined' ? showSeconds : true var d = 0 if (sec >= ONE_DAY_SECONDS) { - d = Math.floor(sec / ONE_DAY_SECONDS); - sec = sec % ONE_DAY_SECONDS; + d = Math.floor(sec / ONE_DAY_SECONDS) + sec = sec % ONE_DAY_SECONDS } - var t = sec % 60; - var n = Math.floor(sec / 3600); - var i = (sec % 3600 - t) / 60; + var t = sec % 60 + var n = Math.floor(sec / 3600) + var i = ((sec % 3600) - t) / 60 if (showSeconds) { - return (d > 0 ? d + 'D ':'') + (n > 9 ? '' + n : '0' + n) + ':' + (i > 9 ? i : '0' + i) + ':' + (t > 9 ? t : '0' + t) + return ( + (d > 0 ? d + 'D ' : '') + (n > 9 ? '' + n : '0' + n) + ':' + (i > 9 ? i : '0' + i) + ':' + (t > 9 ? t : '0' + t) + ) } else { - return (d > 0 ? d + 'D ':'') + (n > 9 ? '' + n : '0' + n) + ':' + (i > 9 ? i : '0' + i) + return (d > 0 ? d + 'D ' : '') + (n > 9 ? '' + n : '0' + n) + ':' + (i > 9 ? i : '0' + i) } - -} \ No newline at end of file +} diff --git a/src/utils/net.util.ts b/src/utils/net.util.ts index 8e084f9..fcaf3cd 100644 --- a/src/utils/net.util.ts +++ b/src/utils/net.util.ts @@ -3,8 +3,6 @@ import fetch, { Response, RequestInit } from 'node-fetch' const TIMEOUT_ERROR = new Error('timeout') -const hexRe = /^[0-9A-Fa-f]+$/gu - /** * Execute fetch and verify that the response was successful. * @@ -214,18 +212,18 @@ export function keyValToObject(str: string, splitChar: string = '&', equalChar = return result } -export const RE_URL_SCHEME = /^(.+?):\/\/.+?$/; +export const RE_URL_SCHEME = /^(.+?):\/\/.+?$/ /** * 获取url中的scheme * @param url * @returns */ export function findUrlScheme(url: string) { - let result = url.match(RE_URL_SCHEME); + let result = url.match(RE_URL_SCHEME) if (!result) { - return ""; + return '' } - return result[1]; + return result[1] } /** @@ -234,13 +232,9 @@ export function findUrlScheme(url: string) { * @returns */ export function decodeJWT(token: string) { - let strings = token.split("."); + let strings = token.split('.') var userinfo = JSON.parse( - decodeURIComponent( - encodeURIComponent( - window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")) - ) - ) - ); - return userinfo; -} \ No newline at end of file + decodeURIComponent(encodeURIComponent(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))), + ) + return userinfo +} diff --git a/src/utils/number.util.ts b/src/utils/number.util.ts index 87a90b0..bc605be 100644 --- a/src/utils/number.util.ts +++ b/src/utils/number.util.ts @@ -233,11 +233,11 @@ function transformNumToChar(num, alphabet) { } /** - * 将num从base进制转为to指定的进制 - * @param {string} numStr 要转换的数字字符串 - * @param {number} base num的进制 - * @param {number} to 转换后的进制 - * @return {string} + * Converts a number from the base specified by `base` to the base specified by `to`. + * @param {string} numStr - The number string to be converted. + * @param {number} base - The base of the number. + * @param {number} to - The target base for the conversion. + * @return {string} - The converted number string. */ export function convert({ numStr, diff --git a/src/utils/promise.util.ts b/src/utils/promise.util.ts index 80512f9..a771bc1 100644 --- a/src/utils/promise.util.ts +++ b/src/utils/promise.util.ts @@ -3,7 +3,7 @@ type RetryOptions = { whitelistErrors: Error[] } /** - * 使用: + * Usage: * retry(() => fetch("https://example.com"), { maxRetries: 3, whitelistErrors: [] }) * .then((response) => console.log(response)) * .catch((error) => console.error(error)); @@ -38,8 +38,8 @@ export function retry(promiseFn: () => Promise, options: RetryOptions): Pr return retryPromise() } /** - * 构建一个promise, 在 - * usage: + * 构建一个promise, 可以在任意时刻resolve或reject + * Usage: * function delay(ms: number): Promise { const deferred = new Deferred(); @@ -95,7 +95,7 @@ export class Deferred { /** * 简单限流的 Promise 队列 - * usage: + * Usage: const q = new PromiseQueue(); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => { q.add( diff --git a/src/utils/security.util.ts b/src/utils/security.util.ts index 5e4d15d..37fc0cf 100644 --- a/src/utils/security.util.ts +++ b/src/utils/security.util.ts @@ -20,22 +20,22 @@ export function genRandomString(length: number) { * @param prob_array 概率数组 */ export function randomWithProb(prob_array: number[]): number { - let total = 0; + let total = 0 for (let _d of prob_array) { - total += _d; + total += _d } - prob_array = prob_array.map((o) => o / total); + prob_array = prob_array.map(o => o / total) // 获取随机数 - let r = Math.random(); + let r = Math.random() // 对概率数组的处理 let s = prob_array .map((v, index) => { - return { index: index, prob: v }; + return { index: index, prob: v } }) - .sort((a, b) => a.prob - b.prob); + .sort((a, b) => a.prob - b.prob) // 判断随机位置 - let result = s.find((v) => (r -= v.prob) <= 0); - return result ? result.index : s.length - 1; + let result = s.find(v => (r -= v.prob) <= 0) + return result ? result.index : s.length - 1 } export function uuid() { diff --git a/src/utils/string.util.ts b/src/utils/string.util.ts index 5aa28cb..b4ff44a 100644 --- a/src/utils/string.util.ts +++ b/src/utils/string.util.ts @@ -169,11 +169,11 @@ export function utf8ToHex(utf8String: string) { */ export function isJsonString(str: string): boolean { try { - if (typeof JSON.parse(str) == "object") { - return true; + if (typeof JSON.parse(str) == 'object') { + return true } } catch (e) {} - return false; + return false } /** * 检查accountId是否符合规则 @@ -182,7 +182,7 @@ export function isJsonString(str: string): boolean { * @returns */ export function checkAccountId(accountId: string) { - return /^\d{4}_\d{4,6}_.+$/.test(accountId); + return /^\d{4}_\d{4,6}_.+$/.test(accountId) } /** * 将accountId拆分出 渠道id, 游戏id, 和openId @@ -190,9 +190,9 @@ export function checkAccountId(accountId: string) { * @returns */ export function parseGameAccountId(accountId: string) { - const arr = accountId.split("_"); - const gameId = arr[1]; - const channel = arr[0]; - const openId = arr[2]; - return { gameId, channel, openId }; -} \ No newline at end of file + const arr = accountId.split('_') + const gameId = arr[1] + const channel = arr[0] + const openId = arr[2] + return { gameId, channel, openId } +}