Files
coconut-leaf/frontend/src/utils/utils.ts
T

56 lines
1.7 KiB
TypeScript
Raw Normal View History

2026-06-30 15:41:34 +08:00
export const DEFAULT_COLOR: string = '#536dfe';
export function gcd(a: number, b: number): number {
if (b == 0) return a;
return gcd(b, a % b);
}
export function lcm(a: number, b: number): number {
return a / gcd(a, b) * b;
}
2026-07-07 21:03:22 +08:00
/**
* 将字符串中的 `{n}` 占位符替换为对应的参数值
* @param str 目标字符串,若为 `null`/`undefined`/空字符串则返回原值或空串(根据需求)
* @param args 用于替换的值列表
* @returns 格式化后的字符串
*/
export function format(str: string, ...args: any[]): string {
// 若 str 为假值(null/undefined/''),直接返回空字符串
if (!str) return '';
return str.replace(/\{(\d+)\}/g, (match, index) => {
const idx = parseInt(index, 10);
const value = args[idx];
// 若参数存在且不为 null/undefined,则转为字符串,否则保留占位符
return value != null ? String(value) : match;
});
}
2026-06-30 15:41:34 +08:00
/**
* Get Monday-first the day of week from given date instead of Sunday-first.
* @param date The date for getting weekday.
* @returns The zero-based weekday. 0 stands for Monday.
*/
export function getWeekday(date: Date): number {
const day = date.getDay();
2026-06-30 15:41:34 +08:00
if (day == 0) return 6;
else return day - 1;
}
2026-07-19 15:57:50 +08:00
/**
* Escape HTML special characters in the string and convert newlines to `<br />`
* so it can be safely inserted via `v-html`. Port of the legacy jQuery-based
* `LineBreaker2Br` (`$('<div>').text(strl).html().replace(/\n/g, '<br />')`).
* @param strl The raw string to convert.
* @returns The escaped, newline-broken HTML string.
*/
export function lineBreaker2Br(strl: string): string {
return strl
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\n/g, '<br />');
}