mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-20 01:38:19 +08:00
util: switch to pure module
This commit is contained in:
3 files changed
+47
-45
No files matched your search
@@ -39,7 +39,7 @@ String.prototype.format ||= function formatStr(...args) {
|
|||||||
}
|
}
|
||||||
} else return this.formatFromArray(args);
|
} else return this.formatFromArray(args);
|
||||||
}
|
}
|
||||||
return result;
|
return result as string;
|
||||||
};
|
};
|
||||||
|
|
||||||
String.prototype.formatFromArray = function formatStr(args) {
|
String.prototype.formatFromArray = function formatStr(args) {
|
||||||
@@ -50,7 +50,7 @@ String.prototype.formatFromArray = function formatStr(args) {
|
|||||||
result = result.replace(reg, args[i]);
|
result = result.replace(reg, args[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result as string;
|
||||||
};
|
};
|
||||||
|
|
||||||
String.prototype.rawformat = function rawFormat(object) {
|
String.prototype.rawformat = function rawFormat(object) {
|
||||||
@@ -73,26 +73,25 @@ try {
|
|||||||
Array.isDiff = diffArray;
|
Array.isDiff = diffArray;
|
||||||
} catch (e) { } // Cannot add property isDiff, object is not extensible
|
} catch (e) { } // Cannot add property isDiff, object is not extensible
|
||||||
|
|
||||||
// @ts-ignore
|
export function formatDate(date: Date, fmt = '%Y-%m-%d %H:%M:%S') {
|
||||||
Date.prototype.format = function formatDate(fmt = '%Y-%m-%d %H:%M:%S') {
|
let m = (date.getMonth() + 1).toString();
|
||||||
let m = this.getMonth() + 1;
|
if (m.length < 2) m = `0${m}`;
|
||||||
if (m < 10) m = `0${m}`;
|
let d = date.getDate().toString();
|
||||||
let d = this.getDate();
|
if (d.length < 2) d = `0${d}`;
|
||||||
if (d < 10) d = `0${d}`;
|
let H = date.getHours().toString();
|
||||||
let H = this.getHours();
|
if (H.length < 2) H = `0${H}`;
|
||||||
if (H < 10) H = `0${H}`;
|
let M = date.getMinutes().toString();
|
||||||
let M = this.getMinutes();
|
if (M.length < 2) M = `0${M}`;
|
||||||
if (M < 10) M = `0${M}`;
|
let S = date.getSeconds().toString();
|
||||||
let S = this.getSeconds();
|
if (S.length < 2) S = `0${S}`;
|
||||||
if (S < 10) S = `0${S}`;
|
|
||||||
return fmt
|
return fmt
|
||||||
.replace('%Y', this.getFullYear())
|
.replace('%Y', date.getFullYear().toString())
|
||||||
.replace('%m', m)
|
.replace('%m', m)
|
||||||
.replace('%d', d)
|
.replace('%d', d)
|
||||||
.replace('%H', H)
|
.replace('%H', H)
|
||||||
.replace('%M', M)
|
.replace('%M', M)
|
||||||
.replace('%S', S);
|
.replace('%S', S);
|
||||||
};
|
}
|
||||||
|
|
||||||
Math.sum = function sum(...args) {
|
Math.sum = function sum(...args) {
|
||||||
let s = 0;
|
let s = 0;
|
||||||
@@ -129,7 +128,7 @@ Set.intersection = function Intersection<T>(A: Set<T> | Array<T> = [], B: Set<T>
|
|||||||
|
|
||||||
export function sleep(timeout: number) {
|
export function sleep(timeout: number) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
setTimeout(() => resolve(true), timeout);
|
setTimeout(resolve, timeout, true);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,11 +136,11 @@ function deepen(modifyString: (source: string) => string) {
|
|||||||
function modifyObject<T>(source: T): T {
|
function modifyObject<T>(source: T): T {
|
||||||
if (typeof source !== 'object' || !source) return source;
|
if (typeof source !== 'object' || !source) return source;
|
||||||
if (Array.isArray(source)) return source.map(modifyObject) as any;
|
if (Array.isArray(source)) return source.map(modifyObject) as any;
|
||||||
const result = {} as T;
|
const result = {} as any;
|
||||||
for (const key in source) {
|
for (const key in source) {
|
||||||
result[modifyString(key)] = modifyObject(source[key]);
|
result[modifyString(key)] = modifyObject(source[key]);
|
||||||
}
|
}
|
||||||
return result;
|
return result as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
return function t<T>(source: T): T {
|
return function t<T>(source: T): T {
|
||||||
@@ -157,9 +156,9 @@ export const paramCase = deepen((source) => source.replace(/_/g, '-').replace(/(
|
|||||||
export const snakeCase = deepen((source) => source.replace(/-/g, '_').replace(/(?<!^)[A-Z]/g, (str) => `_${str.toLowerCase()}`));
|
export const snakeCase = deepen((source) => source.replace(/-/g, '_').replace(/(?<!^)[A-Z]/g, (str) => `_${str.toLowerCase()}`));
|
||||||
|
|
||||||
const TIME_RE = /^([0-9]+(?:\.[0-9]*)?)([mu]?)s?$/i;
|
const TIME_RE = /^([0-9]+(?:\.[0-9]*)?)([mu]?)s?$/i;
|
||||||
const TIME_UNITS = { '': 1000, m: 1, u: 0.001 };
|
const TIME_UNITS = { '': 1000, m: 1, u: 0.001 } as Record<string, number>;
|
||||||
const MEMORY_RE = /^([0-9]+(?:\.[0-9]*)?)([kmg])b?$/i;
|
const MEMORY_RE = /^([0-9]+(?:\.[0-9]*)?)([kmg])b?$/i;
|
||||||
const MEMORY_UNITS = { k: 1 / 1024, m: 1, g: 1024 };
|
const MEMORY_UNITS = { k: 1 / 1024, m: 1, g: 1024 } as Record<string, number>;
|
||||||
|
|
||||||
export function parseTimeMS(str: string | number, throwOnError = true) {
|
export function parseTimeMS(str: string | number, throwOnError = true) {
|
||||||
if (typeof str === 'number' || Number.isSafeInteger(+str)) return +str;
|
if (typeof str === 'number' || Number.isSafeInteger(+str)) return +str;
|
||||||
@@ -199,7 +198,7 @@ export function size(s: number, base = 1) {
|
|||||||
if (s < unit) return '{0} {1}'.format(Math.round(s * 10) / 10, unitName);
|
if (s < unit) return '{0} {1}'.format(Math.round(s * 10) / 10, unitName);
|
||||||
s /= unit;
|
s /= unit;
|
||||||
}
|
}
|
||||||
return `${Math.round(s * unit)} ${unitNames[unitNames.length - 1]}`;
|
return `${Math.round(s * unit)} ${unitNames.at(-1)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function randomPick<T>(arr: T[]): T {
|
export function randomPick<T>(arr: T[]): T {
|
||||||
@@ -217,7 +216,7 @@ export function sortFiles(files: Record<string, any>[] | string[], key = '_id')
|
|||||||
if (!files?.length) return [];
|
if (!files?.length) return [];
|
||||||
const isString = typeof files[0] === 'string';
|
const isString = typeof files[0] === 'string';
|
||||||
const result = files
|
const result = files
|
||||||
.map((i) => (isString ? { name: i, _weights: i.match(fSortR) } : { ...i, _weights: (i[key] || i.name).match(fSortR) }))
|
.map((i: any) => (isString ? { name: i, _weights: i.match(fSortR) } : { ...i, _weights: (i[key] || i.name).match(fSortR) }))
|
||||||
.sort((a, b) => {
|
.sort((a, b) => {
|
||||||
let pos = 0;
|
let pos = 0;
|
||||||
const weightsA = a._weights;
|
const weightsA = a._weights;
|
||||||
@@ -239,7 +238,7 @@ export function sortFiles(files: Record<string, any>[] | string[], key = '_id')
|
|||||||
|
|
||||||
export const getAlphabeticId = (() => {
|
export const getAlphabeticId = (() => {
|
||||||
// A...Z, AA...AZ, BA...BZ, ...
|
// A...Z, AA...AZ, BA...BZ, ...
|
||||||
const f = (a: number) => (a < 0 ? '' : f(a / 26 - 1) + String.fromCharCode((a % 26) + 65)) as string;
|
const f: (a: number) => string = (a: number) => (a < 0 ? '' : f(a / 26 - 1) + String.fromCharCode((a % 26) + 65));
|
||||||
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||||
const cache = alphabet.split('');
|
const cache = alphabet.split('');
|
||||||
for (const ch of alphabet) cache.push(...alphabet.split('').map((c) => ch + c));
|
for (const ch of alphabet) cache.push(...alphabet.split('').map((c) => ch + c));
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import type { Moment } from 'moment';
|
|||||||
import { Exporter, Factory, Logger as Reggol } from 'reggol';
|
import { Exporter, Factory, Logger as Reggol } from 'reggol';
|
||||||
import type * as superagent from 'superagent';
|
import type * as superagent from 'superagent';
|
||||||
|
|
||||||
export * from '@hydrooj/utils/lib/common';
|
// @ts-ignore
|
||||||
|
export * from '@hydrooj/utils/lib/common.ts';
|
||||||
export * as fs from 'fs-extra';
|
export * as fs from 'fs-extra';
|
||||||
|
|
||||||
Factory.formatters['d'] = (value, exporter) => Reggol.color(exporter, 3, value);
|
Factory.formatters['d'] = (value, exporter) => Reggol.color(exporter, 3, value);
|
||||||
@@ -132,22 +133,23 @@ export function bufferToStream(buffer: Buffer): NodeJS.ReadableStream {
|
|||||||
let ObjectId: typeof import('bson').ObjectId; // eslint-disable-line
|
let ObjectId: typeof import('bson').ObjectId; // eslint-disable-line
|
||||||
let isMoment: (x: any) => x is Moment;
|
let isMoment: (x: any) => x is Moment;
|
||||||
|
|
||||||
export namespace Time {
|
export const Time = {
|
||||||
export const second = 1000;
|
second: 1000,
|
||||||
export const minute = second * 60;
|
minute: 60 * 1000,
|
||||||
export const hour = minute * 60;
|
hour: 60 * 60 * 1000,
|
||||||
export const day = hour * 24;
|
day: 24 * 60 * 60 * 1000,
|
||||||
export const week = day * 7;
|
week: 7 * 24 * 60 * 60 * 1000,
|
||||||
export function formatTimeShort(ms: number) {
|
|
||||||
const abs = Math.abs(ms);
|
|
||||||
if (abs >= day - hour / 2) return `${Math.round(ms / day)}d`;
|
|
||||||
if (abs >= hour - minute / 2) return `${Math.round(ms / hour)}h`;
|
|
||||||
if (abs >= minute - second / 2) return `${Math.round(ms / minute)}m`;
|
|
||||||
if (abs >= second) return `${Math.round(ms / second)}s`;
|
|
||||||
return `${ms}ms`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getObjectID(timestamp: string | Date | Moment, allZero = true) {
|
formatTimeShort(ms: number) {
|
||||||
|
const abs = Math.abs(ms);
|
||||||
|
if (abs >= Time.day - Time.hour / 2) return `${Math.round(ms / Time.day)}d`;
|
||||||
|
if (abs >= Time.hour - Time.minute / 2) return `${Math.round(ms / Time.hour)}h`;
|
||||||
|
if (abs >= Time.minute - Time.second / 2) return `${Math.round(ms / Time.minute)}m`;
|
||||||
|
if (abs >= Time.second) return `${Math.round(ms / Time.second)}s`;
|
||||||
|
return `${ms}ms`;
|
||||||
|
},
|
||||||
|
|
||||||
|
getObjectID(timestamp: string | Date | Moment, allZero = true) {
|
||||||
try {
|
try {
|
||||||
ObjectId ||= require('bson').ObjectId;
|
ObjectId ||= require('bson').ObjectId;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -164,8 +166,8 @@ export namespace Time {
|
|||||||
else _timestamp = timestamp.getTime();
|
else _timestamp = timestamp.getTime();
|
||||||
const hexSeconds = Math.floor(_timestamp / 1000).toString(16);
|
const hexSeconds = Math.floor(_timestamp / 1000).toString(16);
|
||||||
return new ObjectId(`${hexSeconds}${allZero ? '0000000000000000' : new ObjectId().toHexString().substring(8)}`);
|
return new ObjectId(`${hexSeconds}${allZero ? '0000000000000000' : new ObjectId().toHexString().substring(8)}`);
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
|
|
||||||
export function errorMessage(err: Error | string) {
|
export function errorMessage(err: Error | string) {
|
||||||
const t = typeof err === 'string' ? err : err.stack;
|
const t = typeof err === 'string' ? err : err.stack;
|
||||||
@@ -358,7 +360,7 @@ export async function pipeRequest(req: superagent.Request, w: fs.WriteStream, ti
|
|||||||
}
|
}
|
||||||
}).catch(reject);
|
}).catch(reject);
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
throw new Error(`Download${e.errno === 'ETIMEDOUT' ? 'Timedout' : 'Error'}(${name ? `${name}, ` : ''}${e.message})`);
|
throw new Error(`Download${e.errno === 'ETIMEDOUT' ? 'Timedout' : 'Error'}(${name ? `${name}, ` : ''}${e.message})`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "@hydrooj/utils",
|
"name": "@hydrooj/utils",
|
||||||
"version": "1.5.4",
|
"version": "1.5.4",
|
||||||
"description": "hydrooj utils",
|
"description": "hydrooj utils",
|
||||||
|
"type": "module",
|
||||||
"main": "lib/utils.ts",
|
"main": "lib/utils.ts",
|
||||||
"repository": "https://github.com/hydro-dev/Hydro.git",
|
"repository": "https://github.com/hydro-dev/Hydro.git",
|
||||||
"author": "undefined <i@undefined.moe>",
|
"author": "undefined <i@undefined.moe>",
|
||||||
@@ -14,11 +15,11 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hydrooj/register": "workspace:^",
|
"@hydrooj/register": "workspace:^",
|
||||||
"cac": "^6.7.14",
|
"cac": "^6.7.14",
|
||||||
"fs-extra": "^11.3.3",
|
"fs-extra": "^11.3.4",
|
||||||
"js-yaml": "^4.1.1",
|
"js-yaml": "^4.1.1",
|
||||||
"reggol": "^2.1.0",
|
"reggol": "^2.1.0",
|
||||||
"search-query-parser": "^1.6.0",
|
"search-query-parser": "^1.6.0",
|
||||||
"systeminformation": "^5.31.1"
|
"systeminformation": "^5.31.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/fs-extra": "^11.0.4"
|
"@types/fs-extra": "^11.0.4"
|
||||||
|
|||||||
Reference in new issue
Block a user