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(' ')
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) => {

View File

@ -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()

View File

@ -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))
}
}
}
};
}

View File

@ -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的字符串
* Format seconds into a string in the format hh:mm:ss
* @param {number} sec
* @param {boolean} showSeconds
* @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)
}
}

View File

@ -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, "/"))
decodeURIComponent(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指定的进制
* @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,

View File

@ -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<T>(promiseFn: () => Promise<T>, options: RetryOptions): Pr
return retryPromise()
}
/**
* promise,
* usage:
* promise, resolve或reject
* Usage:
* function delay(ms: number): Promise<void> {
const deferred = new Deferred<void>();
@ -95,7 +95,7 @@ export class Deferred<T = any> {
/**
* Promise
* usage:
* Usage:
const q = new PromiseQueue();
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].forEach((v) => {
q.add(

View File

@ -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() {

View File

@ -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 };
const arr = accountId.split('_')
const gameId = arr[1]
const channel = arr[0]
const openId = arr[2]
return { gameId, channel, openId }
}