update some comment

This commit is contained in:
CounterFire2023 2024-01-19 15:37:00 +08:00
parent f5404bb3ba
commit 374889ad07
12 changed files with 88 additions and 97 deletions

View File

@ -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'
```

View File

@ -83,25 +83,3 @@ class DeferredPromise<T = void, E = any> {
}) })
} }
} }
// 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()

View File

@ -28,7 +28,7 @@ export function router(route?: string) {
} }
const split = route.split(' ') const split = route.split(' ')
if (split.length > 2) { if (split.length > 2) {
throw new Error('路由中只允许一个空格') throw new Error('Only one space is allowed in @router()')
} }
const [method, path] = split const [method, path] = split
// @ts-ignore // @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[]) { export function dept(depts?: string | string[]) {
return (target: BaseController, name: string, value: PropertyDescriptor) => { return (target: BaseController, name: string, value: PropertyDescriptor) => {

View File

@ -1,12 +1,12 @@
/** /**
* class * Singletonize a class
* 使: * Usage:
* @singleton * @singleton
* class Test {} * class Test {}
* new Test() === new Test() // returns `true` * new Test() === new Test() // returns `true`
* 使 decorator * It can also be used without a decorator
* const TestSingleton = singleton(Test) * const TestSingleton = singleton(Test)
* new TestSingleton() === new TestSingleton() //returns 'true' * new TestSingleton() === new TestSingleton() // returns `true`
*/ */
export const SINGLETON_KEY = Symbol() export const SINGLETON_KEY = Symbol()

View File

@ -80,8 +80,8 @@ export const sign = async ({
/** /**
* convert address to EIP55 format * convert address to EIP55 format
* doc: https://eips.ethereum.org/EIPS/eip-55 * doc: https://eips.ethereum.org/EIPS/eip-55
* @param address * @param address
* @returns * @returns
*/ */
export function toEIP55(address: string) { export function toEIP55(address: string) {
const lowerAddress = `${address}`.toLowerCase().replace('0x', '') const lowerAddress = `${address}`.toLowerCase().replace('0x', '')
@ -137,4 +137,4 @@ export const decodeEvent = (abi: AbiItem, eventData: { data: string; topics: str
} }
} }
return decodedData return decodedData
} }

View File

@ -1,16 +1,16 @@
/** /**
* * Currying a function
* @param func * @param func
* @returns * @returns
*/ */
export function curry(func: (...args0: any[]) => any) { export function curry(func: (...args0: any[]) => any) {
return function curried(this: unknown, ...args: any[]) { return function curried(this: unknown, ...args: any[]) {
if (args.length >= func.length) { if (args.length >= func.length) {
return func.apply(this, args); return func.apply(this, args)
} else { } else {
return function (this: unknown, ...args2: any[]) { return function (this: unknown, ...args2: any[]) {
return curried.apply(this, args.concat(args2)); return curried.apply(this, args.concat(args2))
}; }
} }
}; }
} }

View File

@ -73,7 +73,7 @@ export function calcBetweenDays(time1: number, time2: number) {
} }
/** /**
* * check if the time is today
* @param {number} time * @param {number} time
* @return {boolean} * @return {boolean}
*/ */
@ -106,42 +106,42 @@ export function getThisWeekData(): { startDay: string; endDay: string } {
} }
/** /**
* n周的周一和周日的日期 * Get the start and end dates of the Monday and Sunday of the previous or next n weeks.
* @param {number} n 0, 1, -1 * @param {number} n 0 for the current week, 1 for the next week, -1 for the previous week
* @return {{startDay: string, endDay: string}} * @return {{startDay: string, endDay: string}}
*/ */
export function weekData(n: number): { startDay: string; endDay: string } { export function weekData(n: number): { startDay: string; endDay: string } {
const weekData = { startDay: '', endDay: '' } const weekData = { startDay: '', endDay: '' }
const date = new Date() const date = new Date()
// 上周一的日期
date.setDate(date.getDate() + 7 * n - date.getDay() + 1) date.setDate(date.getDate() + 7 * n - date.getDay() + 1)
weekData.startDay = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() weekData.startDay = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
// 上周日的日期
date.setDate(date.getDate() + 6) date.setDate(date.getDate() + 6)
weekData.endDay = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() weekData.endDay = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
return weekData return weekData
} }
/** /**
* hh:mm:ss的字符串 * Format seconds into a string in the format hh:mm:ss
* @param {number} sec * @param {number} sec
* @param {boolean} showSeconds * @param {boolean} showSeconds Whether to display seconds
*/ */
export const second2str = (sec: number, showSeconds: boolean) => { export const second2str = (sec: number, showSeconds: boolean) => {
showSeconds = typeof showSeconds !== 'undefined' ? showSeconds : true; showSeconds = typeof showSeconds !== 'undefined' ? showSeconds : true
var d = 0 var d = 0
if (sec >= ONE_DAY_SECONDS) { if (sec >= ONE_DAY_SECONDS) {
d = Math.floor(sec / ONE_DAY_SECONDS); d = Math.floor(sec / ONE_DAY_SECONDS)
sec = sec % ONE_DAY_SECONDS; sec = sec % ONE_DAY_SECONDS
} }
var t = sec % 60; var t = sec % 60
var n = Math.floor(sec / 3600); var n = Math.floor(sec / 3600)
var i = (sec % 3600 - t) / 60; var i = ((sec % 3600) - t) / 60
if (showSeconds) { 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 { } 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)
} }
}
}

View File

@ -3,8 +3,6 @@ import fetch, { Response, RequestInit } from 'node-fetch'
const TIMEOUT_ERROR = new Error('timeout') const TIMEOUT_ERROR = new Error('timeout')
const hexRe = /^[0-9A-Fa-f]+$/gu
/** /**
* Execute fetch and verify that the response was successful. * Execute fetch and verify that the response was successful.
* *
@ -214,18 +212,18 @@ export function keyValToObject(str: string, splitChar: string = '&', equalChar =
return result return result
} }
export const RE_URL_SCHEME = /^(.+?):\/\/.+?$/; export const RE_URL_SCHEME = /^(.+?):\/\/.+?$/
/** /**
* url中的scheme * url中的scheme
* @param url * @param url
* @returns * @returns
*/ */
export function findUrlScheme(url: string) { export function findUrlScheme(url: string) {
let result = url.match(RE_URL_SCHEME); let result = url.match(RE_URL_SCHEME)
if (!result) { if (!result) {
return ""; return ''
} }
return result[1]; return result[1]
} }
/** /**
@ -234,13 +232,9 @@ export function findUrlScheme(url: string) {
* @returns * @returns
*/ */
export function decodeJWT(token: string) { export function decodeJWT(token: string) {
let strings = token.split("."); let strings = token.split('.')
var userinfo = JSON.parse( var userinfo = JSON.parse(
decodeURIComponent( decodeURIComponent(encodeURIComponent(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))),
encodeURIComponent( )
window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")) return userinfo
) }
)
);
return userinfo;
}

View File

@ -233,11 +233,11 @@ function transformNumToChar(num, alphabet) {
} }
/** /**
* num从base进制转为to指定的进制 * Converts a number from the base specified by `base` to the base specified by `to`.
* @param {string} numStr * @param {string} numStr - The number string to be converted.
* @param {number} base num的进制 * @param {number} base - The base of the number.
* @param {number} to * @param {number} to - The target base for the conversion.
* @return {string} * @return {string} - The converted number string.
*/ */
export function convert({ export function convert({
numStr, numStr,

View File

@ -3,7 +3,7 @@ type RetryOptions = {
whitelistErrors: Error[] whitelistErrors: Error[]
} }
/** /**
* 使: * Usage:
* retry(() => fetch("https://example.com"), { maxRetries: 3, whitelistErrors: [] }) * retry(() => fetch("https://example.com"), { maxRetries: 3, whitelistErrors: [] })
* .then((response) => console.log(response)) * .then((response) => console.log(response))
* .catch((error) => console.error(error)); * .catch((error) => console.error(error));
@ -38,8 +38,8 @@ export function retry<T>(promiseFn: () => Promise<T>, options: RetryOptions): Pr
return retryPromise() return retryPromise()
} }
/** /**
* promise, * promise, resolve或reject
* usage: * Usage:
* function delay(ms: number): Promise<void> { * function delay(ms: number): Promise<void> {
const deferred = new Deferred<void>(); const deferred = new Deferred<void>();
@ -95,7 +95,7 @@ export class Deferred<T = any> {
/** /**
* Promise * Promise
* usage: * Usage:
const q = new PromiseQueue(); const q = new PromiseQueue();
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => { [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => {
q.add( q.add(

View File

@ -20,22 +20,22 @@ export function genRandomString(length: number) {
* @param prob_array * @param prob_array
*/ */
export function randomWithProb(prob_array: number[]): number { export function randomWithProb(prob_array: number[]): number {
let total = 0; let total = 0
for (let _d of prob_array) { 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 let s = prob_array
.map((v, index) => { .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); let result = s.find(v => (r -= v.prob) <= 0)
return result ? result.index : s.length - 1; return result ? result.index : s.length - 1
} }
export function uuid() { export function uuid() {

View File

@ -169,11 +169,11 @@ export function utf8ToHex(utf8String: string) {
*/ */
export function isJsonString(str: string): boolean { export function isJsonString(str: string): boolean {
try { try {
if (typeof JSON.parse(str) == "object") { if (typeof JSON.parse(str) == 'object') {
return true; return true
} }
} catch (e) {} } catch (e) {}
return false; return false
} }
/** /**
* accountId是否符合规则 * accountId是否符合规则
@ -182,7 +182,7 @@ export function isJsonString(str: string): boolean {
* @returns * @returns
*/ */
export function checkAccountId(accountId: string) { 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 * accountId拆分出 id, id, openId
@ -190,9 +190,9 @@ export function checkAccountId(accountId: string) {
* @returns * @returns
*/ */
export function parseGameAccountId(accountId: string) { export function parseGameAccountId(accountId: string) {
const arr = accountId.split("_"); const arr = accountId.split('_')
const gameId = arr[1]; const gameId = arr[1]
const channel = arr[0]; const channel = arr[0]
const openId = arr[2]; const openId = arr[2]
return { gameId, channel, openId }; return { gameId, channel, openId }
} }