init project
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
export type EventArguments = readonly unknown[];
|
||||
|
||||
type EventCallback<Arguments extends EventArguments> = (...args: Arguments) => void;
|
||||
|
||||
interface EventListener {
|
||||
callback: unknown;
|
||||
invoke: (args: EventArguments) => void;
|
||||
}
|
||||
|
||||
type EventArgumentsOf<EventMap extends object, Key extends keyof EventMap> = EventMap[Key] extends EventArguments
|
||||
? EventMap[Key]
|
||||
: never;
|
||||
|
||||
/** 强类型的进程内事件管理。 */
|
||||
export default class Events<EventMap extends object> {
|
||||
private readonly listeners = new Map<keyof EventMap, EventListener[]>();
|
||||
|
||||
/** 注册事件(会叠加)。 */
|
||||
public register<Key extends keyof EventMap>(key: Key, callback: EventCallback<EventArgumentsOf<EventMap, Key>>): () => void {
|
||||
const listener: EventListener = {
|
||||
callback,
|
||||
invoke: args => callback(...(args as EventArgumentsOf<EventMap, Key>))
|
||||
};
|
||||
const observers = this.listeners.get(key) ?? [];
|
||||
observers.push(listener);
|
||||
this.listeners.set(key, observers);
|
||||
return () => this.removeListener(key, callback);
|
||||
}
|
||||
|
||||
/** 重置并注册事件(不会叠加)。 */
|
||||
public reset<Key extends keyof EventMap>(key: Key, callback: EventCallback<EventArgumentsOf<EventMap, Key>>): void {
|
||||
this.listeners.set(key, []);
|
||||
this.register(key, callback);
|
||||
}
|
||||
|
||||
/** 移除指定事件的全部监听。 */
|
||||
public remove<Key extends keyof EventMap>(key: Key): void {
|
||||
this.listeners.delete(key);
|
||||
}
|
||||
|
||||
/** 移除指定事件的单个监听。 */
|
||||
public removeListener<Key extends keyof EventMap>(key: Key, callback: EventCallback<EventArgumentsOf<EventMap, Key>>): void {
|
||||
const observers = this.listeners.get(key);
|
||||
if (!observers) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextObservers = observers.filter(observer => observer.callback !== callback);
|
||||
if (nextObservers.length) {
|
||||
this.listeners.set(key, nextObservers);
|
||||
} else {
|
||||
this.listeners.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/** 触发事件。 */
|
||||
public emit<Key extends keyof EventMap>(key: Key, ...args: EventArgumentsOf<EventMap, Key>): void {
|
||||
const observers = this.listeners.get(key);
|
||||
if (!observers) {
|
||||
return;
|
||||
}
|
||||
for (const observer of [...observers]) {
|
||||
observer.invoke(args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import Text from "./Text";
|
||||
|
||||
export const UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB"] as const;
|
||||
export type Unit = (typeof UNITS)[number];
|
||||
|
||||
/** 存储容量工具。 */
|
||||
export default class IOSize {
|
||||
public static BYTE = 1;
|
||||
public static KB = IOSize.BYTE << 10;
|
||||
public static MB = IOSize.KB << 10;
|
||||
public static GB = IOSize.MB << 10;
|
||||
public static TB = IOSize.GB << 10;
|
||||
public static PB = IOSize.TB << 10;
|
||||
public static EB = IOSize.PB << 10;
|
||||
|
||||
public static format(size?: number | null, fixed = 2, stopUnit?: Unit): string {
|
||||
if (size === undefined || size === null || size <= 0) {
|
||||
return "0 B";
|
||||
}
|
||||
let value = size;
|
||||
for (let index = 0; index < UNITS.length; index += 1) {
|
||||
const unit = UNITS[index];
|
||||
if (value <= 1000 || index === UNITS.length - 1 || unit === stopUnit) {
|
||||
return index === 0 ? `${value} B` : `${value.toFixed(fixed)} ${unit}`;
|
||||
}
|
||||
value /= 1024;
|
||||
}
|
||||
return "0 B";
|
||||
}
|
||||
|
||||
public static parse(sizeString?: string | null): number {
|
||||
if (sizeString === undefined || sizeString === null || !sizeString.trim()) {
|
||||
return 0;
|
||||
}
|
||||
const normalized = sizeString.trim();
|
||||
const matcher = /^([-+]?\d+(?:\.\d+)?)\s*([a-zA-Z]+)$/.exec(normalized);
|
||||
if (!matcher) {
|
||||
if (/^\d+$/.test(normalized)) {
|
||||
return Number.parseInt(normalized, 10);
|
||||
}
|
||||
throw new Error(`invalid size format: ${sizeString}`);
|
||||
}
|
||||
|
||||
const value = Number.parseFloat(matcher[1]);
|
||||
if (value < 0) {
|
||||
throw new Error(`size cannot be negative: ${value}`);
|
||||
}
|
||||
const rawUnit = matcher[2].toUpperCase();
|
||||
const unit = UNITS.includes(rawUnit as Unit)
|
||||
? rawUnit as Unit
|
||||
: ({ K: "KB", M: "MB", G: "GB", T: "TB", P: "PB", E: "EB", B: "B" } as Record<string, Unit>)[rawUnit[0]];
|
||||
if (!unit) {
|
||||
throw new Error(`Unknown unit: ${rawUnit}`);
|
||||
}
|
||||
return Math.round(value * Math.pow(1024, UNITS.indexOf(unit)));
|
||||
}
|
||||
|
||||
public static speed(value?: number | null): string {
|
||||
return value === undefined || value === null ? "" : Text.unit(this.format(value, 2), " / s");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
export class MethodLocker<R> {
|
||||
private isLocked = false;
|
||||
private queue: Array<{
|
||||
task: () => Promise<R>;
|
||||
resolve: (value: R | PromiseLike<R>) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
}> = [];
|
||||
|
||||
/** 串行执行异步任务,后续任务会按提交顺序等待。 */
|
||||
public execute(task: () => Promise<R>): Promise<R> {
|
||||
return new Promise<R>((resolve, reject) => {
|
||||
this.queue.push({ task, resolve, reject });
|
||||
void this.dequeue();
|
||||
});
|
||||
}
|
||||
|
||||
private async dequeue(): Promise<void> {
|
||||
if (this.isLocked) {
|
||||
return;
|
||||
}
|
||||
const nextTask = this.queue.shift();
|
||||
if (!nextTask) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isLocked = true;
|
||||
try {
|
||||
nextTask.resolve(await nextTask.task());
|
||||
} catch (error) {
|
||||
nextTask.reject(error);
|
||||
} finally {
|
||||
this.isLocked = false;
|
||||
void this.dequeue();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
export const PrismjsType = {
|
||||
PlainText: "PlainText",
|
||||
Markdown: "Markdown",
|
||||
JavaScript: "JavaScript",
|
||||
TypeScript: "TypeScript",
|
||||
Initialization: "Initialization",
|
||||
PHP: "PHP",
|
||||
SQL: "SQL",
|
||||
XML: "XML",
|
||||
CSS: "CSS",
|
||||
VUE: "VUE",
|
||||
LESS: "LESS",
|
||||
Markup: "Markup",
|
||||
YAML: "YAML",
|
||||
Json: "Json",
|
||||
Java: "Java",
|
||||
Properties: "Properties",
|
||||
NginxConf: "NginxConf",
|
||||
ApacheConf: "ApacheConf"
|
||||
} as const;
|
||||
|
||||
export type PrismjsType = (typeof PrismjsType)[keyof typeof PrismjsType];
|
||||
|
||||
export const PrismjsViewer = {
|
||||
MARKDOWN: "MARKDOWN",
|
||||
CODE: "CODE",
|
||||
TEXT: "TEXT"
|
||||
} as const;
|
||||
|
||||
export type PrismjsViewer = (typeof PrismjsViewer)[keyof typeof PrismjsViewer];
|
||||
|
||||
export type PrismjsProperties = {
|
||||
extensions: string[];
|
||||
prismjs: string;
|
||||
viewer: PrismjsViewer;
|
||||
};
|
||||
|
||||
/** 文件类型元数据,不包含 Prism.js 或 DOM 运行时。 */
|
||||
export default class Prismjs {
|
||||
private static instance: Prismjs;
|
||||
readonly map = new Map<PrismjsType, PrismjsProperties>();
|
||||
|
||||
private constructor() {
|
||||
this.map.set(PrismjsType.PlainText, { extensions: ["txt"], prismjs: "", viewer: PrismjsViewer.TEXT });
|
||||
this.map.set(PrismjsType.Markdown, { extensions: ["md"], prismjs: "md", viewer: PrismjsViewer.MARKDOWN });
|
||||
this.map.set(PrismjsType.JavaScript, { extensions: ["js"], prismjs: "js", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.VUE, { extensions: ["vue"], prismjs: "html", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.TypeScript, { extensions: ["ts"], prismjs: "ts", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.Initialization, { extensions: ["ini"], prismjs: "ini", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.PHP, { extensions: ["php"], prismjs: "php", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.SQL, { extensions: ["sql"], prismjs: "sql", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.XML, { extensions: ["xml", "fxml", "wxml"], prismjs: "xml", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.CSS, { extensions: ["css", "wxss"], prismjs: "css", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.LESS, { extensions: ["less"], prismjs: "less", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.Markup, { extensions: ["htm", "html"], prismjs: "markup", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.YAML, { extensions: ["yml", "yaml"], prismjs: "yaml", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.Json, { extensions: ["json"], prismjs: "json", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.Java, { extensions: ["java"], prismjs: "java", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.Properties, { extensions: ["properties"], prismjs: "properties", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.NginxConf, { extensions: [], prismjs: "nginx", viewer: PrismjsViewer.CODE });
|
||||
this.map.set(PrismjsType.ApacheConf, { extensions: [], prismjs: "apacheconf", viewer: PrismjsViewer.CODE });
|
||||
}
|
||||
|
||||
private static getInstance(): Prismjs {
|
||||
Prismjs.instance ??= new Prismjs();
|
||||
return Prismjs.instance;
|
||||
}
|
||||
|
||||
public static typeFromFileName(fileName: string): PrismjsType | undefined {
|
||||
const extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
|
||||
if (!extension) {
|
||||
return undefined;
|
||||
}
|
||||
for (const [type, properties] of this.getInstance().map) {
|
||||
if (properties.extensions.includes(extension)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public static getFileProperties(type: PrismjsType): PrismjsProperties | undefined {
|
||||
return this.getInstance().map.get(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
export default class Text {
|
||||
public static keyValue(obj: object, assign: string, split: string): string {
|
||||
let result = "";
|
||||
Object.entries(obj).forEach(([key, value]) => {
|
||||
result += `${key}${assign}${value}${split}`;
|
||||
});
|
||||
return result.substring(0, result.length - split.length);
|
||||
}
|
||||
|
||||
public static urlArgs(obj?: Record<string, unknown>): string {
|
||||
if (!obj) {
|
||||
return "";
|
||||
}
|
||||
const args: string[] = [];
|
||||
Object.entries(obj).forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach(item => {
|
||||
args.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(item))}`);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (value !== undefined && value !== null) {
|
||||
args.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
|
||||
}
|
||||
});
|
||||
return args.join("&");
|
||||
}
|
||||
|
||||
public static template(template: string, variables: Record<string, unknown>): string {
|
||||
return template.replace(/\$\{(\w+)}/g, (_, key: string) => String(variables[key]));
|
||||
}
|
||||
|
||||
public static pad(value: number | string, length = 2, fill = "0"): string {
|
||||
return value.toString().padStart(length, fill);
|
||||
}
|
||||
|
||||
public static unitCompact(value: number | string | null | undefined, unit: string, fixed = 0): string {
|
||||
return this.unit(value, unit, fixed, true);
|
||||
}
|
||||
|
||||
public static unit(value: number | string | null | undefined, unit: string, fixed = 0, compact = false): string {
|
||||
if (value === null || value === undefined) {
|
||||
return "";
|
||||
}
|
||||
if (typeof value === "string" && !value.trim()) {
|
||||
return "";
|
||||
}
|
||||
const text = typeof value === "number"
|
||||
? Number.isNaN(value) ? "" : value.toFixed(fixed)
|
||||
: value.trim();
|
||||
return text ? `${text}${compact ? "" : " "}${unit}` : "";
|
||||
}
|
||||
|
||||
public static display(value: string | number | null | undefined): string {
|
||||
if (typeof value === "string") {
|
||||
return value.trim();
|
||||
}
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value.toString();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static displayBool(value: boolean | null | undefined, onTrue = "true", onFalse = "false"): string {
|
||||
if (value === null || value === undefined) {
|
||||
return "";
|
||||
}
|
||||
return value ? onTrue : onFalse;
|
||||
}
|
||||
|
||||
/** 根据背景色返回更易读的文本色。 */
|
||||
public static readableColor(color: string): "#111" | "#FFF" {
|
||||
const match = color.trim().match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);
|
||||
if (!match) {
|
||||
return "#111";
|
||||
}
|
||||
const hex = match[1];
|
||||
const rgb = hex.length === 3
|
||||
? [parseInt(hex[0] + hex[0], 16), parseInt(hex[1] + hex[1], 16), parseInt(hex[2] + hex[2], 16)]
|
||||
: [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)];
|
||||
const luminance = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2];
|
||||
return luminance < 186 ? "#FFF" : "#111";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import Toolkit from "./Toolkit";
|
||||
import Text from "./Text";
|
||||
|
||||
export default class Time {
|
||||
public static S = 1E3;
|
||||
public static M = Time.S * 60;
|
||||
public static H = Time.M * 60;
|
||||
public static D = Time.H * 24;
|
||||
|
||||
public static now(): number {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
public static toTimestamp(date: Date): number {
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
public static toDateObject(unix?: number | Date): Date | undefined {
|
||||
if (!unix) return undefined;
|
||||
return unix instanceof Date ? unix : new Date(unix);
|
||||
}
|
||||
|
||||
public static toTime(unix?: number | Date): string {
|
||||
if (!unix) return "";
|
||||
const date = unix instanceof Date ? unix : new Date(unix);
|
||||
return `${Text.pad(date.getHours())}:${Text.pad(date.getMinutes())}`;
|
||||
}
|
||||
|
||||
public static toLongTime(unix?: number): string {
|
||||
if (!unix) return "";
|
||||
const date = new Date(unix);
|
||||
return `${Text.pad(date.getHours())}:${Text.pad(date.getMinutes())}:${Text.pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
public static toShortTime(unix?: number): string {
|
||||
if (!unix) return "";
|
||||
const date = new Date(unix);
|
||||
return `${Text.pad(date.getMinutes())}:${Text.pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
public static toDate(unix?: number | Date): string {
|
||||
const date = this.toDateObject(unix);
|
||||
if (date) {
|
||||
return `${date.getFullYear()}-${Text.pad(date.getMonth() + 1)}-${Text.pad(date.getDate())}`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static toDateTime(unix?: number | Date): string {
|
||||
return unix ? `${this.toDate(unix)} ${this.toTime(unix)}` : "";
|
||||
}
|
||||
|
||||
public static toLongDateTime(unix?: number): string {
|
||||
return unix ? `${this.toDate(unix)} ${this.toLongTime(unix)}` : "";
|
||||
}
|
||||
|
||||
/** 格式化相对日期;较远的时间显示为具体日期。 */
|
||||
public static formatDate(unix?: number): string {
|
||||
return this.formatDateTime(unix, false);
|
||||
}
|
||||
|
||||
/** 格式化过去或未来的时间,返回相对描述或具体日期时间。 */
|
||||
public static formatDateTime(unix?: number, withDetailTime = true): string {
|
||||
if (!unix) return "";
|
||||
const difference = unix - Date.now();
|
||||
const duration = Math.abs(difference);
|
||||
if (Time.D * 4 < duration) {
|
||||
return withDetailTime ? this.toDateTime(unix) : this.toDate(unix);
|
||||
}
|
||||
const isFuture = 0 < difference;
|
||||
return this.formatRelativeTime(duration, isFuture ? "后" : "前", isFuture ? "稍后" : "刚刚");
|
||||
}
|
||||
|
||||
/** 将非负时间间隔转换为相对时间文案。 */
|
||||
private static formatRelativeTime(duration: number, suffix: "前" | "后", fallback: "刚刚" | "稍后"): string {
|
||||
if (duration < Time.M) return fallback;
|
||||
if (duration < Time.H) return `${Math.floor(duration / Time.M)} 分钟${suffix}`;
|
||||
if (duration < Time.D) return `${Math.floor(duration / Time.H)} 小时${suffix}`;
|
||||
return `${Math.floor(duration / Time.D)} 天${suffix}`;
|
||||
}
|
||||
|
||||
public static between(begin: Date, end = new Date()): {
|
||||
l: number;
|
||||
y: number;
|
||||
d: number;
|
||||
h: number;
|
||||
m: number;
|
||||
s: number;
|
||||
ms: number
|
||||
} {
|
||||
const second = 1E3;
|
||||
const minute = 6E4;
|
||||
const hour = 36E5;
|
||||
const day = 864E5;
|
||||
const year = 31536E6;
|
||||
const length = end.getTime() - begin.getTime();
|
||||
const y = Math.floor(length / year);
|
||||
const d = Math.floor(length / day - y * 365);
|
||||
const h = Math.floor((length - (y * 365 + d) * day) / hour);
|
||||
const m = Math.floor((length - (y * 365 + d) * day - h * hour) / minute);
|
||||
const s = Math.floor((length - (y * 365 + d) * day - h * hour - m * minute) / second);
|
||||
const ms = Math.floor(((length - (y * 365 + d) * day - h * hour - m * minute) / second - s) * second);
|
||||
return { l: length, y, d, h, m, s, ms };
|
||||
}
|
||||
|
||||
public static duration(totalMs?: number | null, includeMilliseconds = false): string {
|
||||
if (totalMs === null || totalMs === undefined) return "";
|
||||
let remain = Math.floor(totalMs);
|
||||
const years = Math.floor(remain / (Time.D * 365));
|
||||
remain %= Time.D * 365;
|
||||
const days = Math.floor(remain / Time.D);
|
||||
remain %= Time.D;
|
||||
const hours = Math.floor(remain / Time.H);
|
||||
remain %= Time.H;
|
||||
const minutes = Math.floor(remain / Time.M);
|
||||
remain %= Time.M;
|
||||
const seconds = Math.floor(remain / Time.S);
|
||||
remain %= Time.S;
|
||||
const parts: string[] = [];
|
||||
Toolkit.doWhere(years > 0, () => parts.push(`${years} 年`));
|
||||
Toolkit.doWhere(days > 0, () => parts.push(`${days} 天`));
|
||||
Toolkit.doWhere(hours > 0, () => parts.push(`${hours} 小时`));
|
||||
Toolkit.doWhere(minutes > 0, () => parts.push(`${minutes} 分钟`));
|
||||
Toolkit.doWhere(seconds > 0, () => parts.push(`${seconds} 秒`));
|
||||
Toolkit.doWhere(includeMilliseconds && remain > 0, () => parts.push(`${remain} 毫秒`));
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
public static toMediaTime(seconds: number): string {
|
||||
const value = Math.floor(seconds);
|
||||
const hours = Math.floor(value / 3600);
|
||||
const minutes = Math.floor((value % 3600) / 60);
|
||||
const second = value % 60;
|
||||
return hours > 0 ? `${hours}:${Text.pad(minutes)}:${Text.pad(second)}` : `${Text.pad(minutes)}:${Text.pad(second)}`;
|
||||
}
|
||||
|
||||
public static parseToMS(timeString: string): number {
|
||||
if (!timeString || !timeString.trim()) throw new Error("not found timeStr");
|
||||
const matcher = /^(\d+(?:\.\d+)?)(ms|[dhms])?$/.exec(timeString.replace(/\s+/g, "").toLowerCase());
|
||||
if (!matcher) throw new Error(`invalid format: ${timeString}`);
|
||||
const value = Number.parseFloat(matcher[1]);
|
||||
switch (matcher[2]) {
|
||||
case "s":
|
||||
return Math.round(value * Time.S);
|
||||
case "m":
|
||||
return Math.round(value * Time.M);
|
||||
case "h":
|
||||
return Math.round(value * Time.H);
|
||||
case "d":
|
||||
return Math.round(value * Time.D);
|
||||
default:
|
||||
return Math.round(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
export default class Toolkit {
|
||||
public static isFunction(value: unknown): value is (...args: any[]) => any { return typeof value === "function"; }
|
||||
public static isArray(value: unknown): value is unknown[] { return Array.isArray(value); }
|
||||
public static isString(value: unknown): value is string { return typeof value === "string"; }
|
||||
public static isSymbol(value: unknown): value is symbol { return typeof value === "symbol"; }
|
||||
public static isObject(value: unknown): value is Record<string, unknown> { return value !== null && typeof value === "object"; }
|
||||
public static isNumber(value: unknown): value is number { return typeof value === "number" && !Number.isNaN(value); }
|
||||
|
||||
public static guid(): string {
|
||||
const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
|
||||
return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
|
||||
}
|
||||
|
||||
public static className(...values: unknown[]): string {
|
||||
const classes: string[] = [];
|
||||
values.forEach(value => {
|
||||
if (!value) return;
|
||||
if (this.isString(value)) classes.push(value);
|
||||
else if (this.isArray(value)) {
|
||||
const nested = this.className(...value);
|
||||
if (nested) classes.push(nested);
|
||||
} else if (this.isObject(value)) {
|
||||
Object.entries(value).forEach(([name, enabled]) => { if (enabled) classes.push(name); });
|
||||
}
|
||||
});
|
||||
return classes.join(" ");
|
||||
}
|
||||
|
||||
public static isEmpty(value: unknown): boolean {
|
||||
if (this.isString(value)) return value.trim().length === 0;
|
||||
if (this.isArray(value)) return value.length === 0;
|
||||
if (this.isFunction(value)) return this.isEmpty(value());
|
||||
return value === undefined || value === null;
|
||||
}
|
||||
|
||||
public static isNotEmpty(value: unknown): boolean { return !this.isEmpty(value); }
|
||||
|
||||
public static async sleep(milliseconds: number): Promise<void> {
|
||||
await new Promise<void>(resolve => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
public static toNumber(value: string, fallback?: number): number | undefined {
|
||||
if (!value) return fallback;
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : fallback;
|
||||
}
|
||||
|
||||
public static async(callback: (...args: any[]) => any): void { setTimeout(callback, 0); }
|
||||
|
||||
public static random(min = 0, max = 100): number { return Math.floor(Math.random() * (max + 1 - min)) + min; }
|
||||
|
||||
public static randomDouble(min = 0, max = 1): number { return Math.random() * (max - min) + min; }
|
||||
|
||||
public static deepClone<T>(origin: T): T {
|
||||
if (origin === null || typeof origin !== "object") return origin;
|
||||
if (Array.isArray(origin)) return origin.map(item => this.deepClone(item)) as T;
|
||||
const result: Record<string, unknown> = {};
|
||||
Object.entries(origin as Record<string, unknown>).forEach(([key, value]) => { result[key] = this.deepClone(value); });
|
||||
return result as T;
|
||||
}
|
||||
|
||||
public static toObject(map: Map<unknown, unknown>): Record<string, unknown> {
|
||||
return Array.from(map.entries()).reduce<Record<string, unknown>>((result, [key, value]) => {
|
||||
result[String(key)] = value ?? null;
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
public static uuid(): string {
|
||||
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
const lengths = [8, 4, 4, 4, 12];
|
||||
return lengths.map(length => {
|
||||
let value = "";
|
||||
for (let index = 0; index < length; index += 1) value += chars[this.random(0, chars.length - 1)];
|
||||
return value;
|
||||
}).join("-");
|
||||
}
|
||||
|
||||
public static keyFromValue<T extends Record<string, unknown>>(object: T, value: unknown): string | undefined {
|
||||
return Object.keys(object).find(key => object[key] === value);
|
||||
}
|
||||
|
||||
public static debounce<T extends (...args: any[]) => any>(callback: T, immediate = true, delay = 300): ((...args: Parameters<T>) => void) & { cancel(): void } {
|
||||
let timerId: ReturnType<typeof setTimeout> | null = null;
|
||||
let leading = immediate;
|
||||
const cancel = () => {
|
||||
if (timerId !== null) { clearTimeout(timerId); timerId = null; }
|
||||
leading = immediate;
|
||||
};
|
||||
const debounced = (...args: Parameters<T>): void => {
|
||||
if (timerId !== null) { clearTimeout(timerId); timerId = null; }
|
||||
if (leading) {
|
||||
callback(...args);
|
||||
leading = false;
|
||||
timerId = setTimeout(() => { leading = immediate; timerId = null; }, delay);
|
||||
} else {
|
||||
timerId = setTimeout(() => { callback(...args); leading = immediate; timerId = null; }, delay);
|
||||
}
|
||||
};
|
||||
debounced.cancel = cancel;
|
||||
return debounced as ((...args: Parameters<T>) => void) & { cancel(): void };
|
||||
}
|
||||
|
||||
public static doWhere(condition: boolean | (() => boolean), callback: () => void): void {
|
||||
if (typeof condition === "function" ? condition() : condition) callback();
|
||||
}
|
||||
|
||||
public static doNotNull<T>(value: T | null | undefined, callback: (value: T) => void): void {
|
||||
if (value) callback(value);
|
||||
}
|
||||
|
||||
public static setRandomInterval(config: {
|
||||
handler: (() => void) | ((value: number) => void);
|
||||
handleRate?: number;
|
||||
interval?: number;
|
||||
min?: number;
|
||||
max?: number;
|
||||
}): ReturnType<typeof setInterval> {
|
||||
const { handler, handleRate = 1, interval, min, max } = config;
|
||||
return setInterval(() => {
|
||||
if (Math.random() >= handleRate) return;
|
||||
if (min !== undefined && max !== undefined) (handler as (value: number) => void)(this.randomDouble(min, max));
|
||||
else (handler as () => void)();
|
||||
}, interval);
|
||||
}
|
||||
|
||||
public static formatJson(jsonValue?: string | object): string {
|
||||
if (jsonValue === undefined || jsonValue === null) return "";
|
||||
if (typeof jsonValue === "string") {
|
||||
const value = jsonValue.trim();
|
||||
if (!value) return "";
|
||||
try { return JSON.stringify(JSON.parse(value), null, 4); } catch { return value; }
|
||||
}
|
||||
return JSON.stringify(jsonValue, null, 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export { default as Events } from "./Events";
|
||||
export { default as IOSize } from "./IOSize";
|
||||
export { default as Prismjs } from "./Prismjs";
|
||||
export { default as Text } from "./Text";
|
||||
export { default as Time } from "./Time";
|
||||
export { default as Toolkit } from "./Toolkit";
|
||||
|
||||
export * from "./IOSize";
|
||||
export * from "./MethodLocker";
|
||||
export * from "./Prismjs";
|
||||
Reference in New Issue
Block a user