123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- export function debounce(fn: Function, delay = 200, immediate = false) {
- let timer: ReturnType<typeof setTimeout>;
- return function (...args: any) {
- const context = globalThis;
- let result: unknown;
- args = arguments;
- if (timer) {
- clearTimeout(timer);
- }
- if (immediate && !timer) {
- result = fn.apply(context, args);
- }
- timer = setTimeout(() => {
- result = fn.apply(context, args);
- }, delay);
- return result;
- };
- }
- export const phoneConvert = (number: string) => {
- if (!number) return "";
- let pat = /(\d{3})\d*(\d{3})/;
- return number.replace(pat, "$1****$2");
- };
- /**
- * @description 根据语言获取时区
- */
- const language = ["pt-BR", "zh-CN", "en-US"];
- function getLang(utc: string) {
- let reg = new RegExp(utc, "i");
- const i = language.findIndex((n, index) => {
- if (reg.test(n)) {
- return index;
- }
- });
- let n = i < 0 ? 0 : i;
- return language[n];
- }
- export const timeFormat = (
- time: number,
- lang = "en",
- delimiter?: undefined | string,
- day = false
- ): string => {
- if (!time) return "";
- const len = (time + "").length;
- if (len === 10) {
- time = time * 1000;
- }
- lang = getLang(lang);
- if (delimiter) {
- return new Date(time)
- .toLocaleString(lang, {
- hour12: false,
- })
- .replaceAll("/", delimiter);
- }
- if (day) {
- return new Date(time).toLocaleString(lang, {
- year: "2-digit",
- month: "2-digit",
- day: "2-digit",
- hour12: false,
- });
- }
- return new Date(time).toLocaleString(lang, {
- year: "2-digit",
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- hour12: false,
- });
- };
- /**
- * @description 复制文本
- */
- export let copyText = function (text: string) {
- if (navigator.clipboard) {
- copyText = (text: string) => {
- navigator.clipboard.writeText(text);
- };
- } else {
- copyText = (text) => {
- const input = document.createElement("input");
- input.setAttribute("value", text);
- document.body.appendChild(input);
- input.select();
- document.execCommand("copy");
- document.body.removeChild(input);
- };
- }
- copyText(text);
- };
- /**
- * @description 两个数值计算百分比
- * @param {current} 当前值
- * @param {source} 总值
- * @return number
- */
- export const percentage = (current: number, source: number) => {
- if (!source) return 0;
- const num = (current * 100) / source;
- return num > 100 ? 100 : flatPoint(num);
- };
- /**
- * @description 保留两位数浮点数
- */
- export const flatPoint = (num: number) => {
- return Number(num.toFixed(2));
- };
- /**
- * @description 是否是移动端
- */
- export function isMobile(): boolean {
- try {
- document.createEvent("TouchEvent");
- return true;
- } catch (e) {
- return false;
- }
- }
|