tiefen_space_app/utils/tools.js

73 lines
1.9 KiB
JavaScript

export function utf8Length(str) {
let length = 0;
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code < 0x80) {
// 0xxxxxxx
length += 0.5;
} else if (code < 0x800) {
// 110xxxxx 10xxxxxx
length += 2;
} else if (code < 0x10000) {
// 1110xxxx 10xxxxxx 10xxxxxx
length += 1;
} else if (code <= 0x10ffff) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
length += 4;
}
}
return length;
}
//格式化时间
export function formatDate(timestamp) {
const nowTime = new Date();
const date = new Date(timestamp * 1000);
const year = date.getFullYear();
const month = date.getMonth() + 1; // 月份从0开始,所以需要加1
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
if (nowTime.getTime() - 24 * 60 * 60 * 1000 > date.getTime()) {
return `${month}/${day}`;
} else {
return `${hours}:${minutes > 9 ? minutes : "0" + minutes}`;
}
}
// 防抖函数
export function debounce(fn, delay) {
let timer = null;
return (fnn) => {
//清除上一次的延时器
if (timer) {
clearTimeout(timer);
// return;
// console.log(timer);
}
//重新设置新的延时器
timer = setTimeout(() => {
//修改this指向问题
// fn.apply(this,value)
fn(fnn);
}, delay);
};
}
// 跳转页面
export function goToPage({ url, action }) {
if (action !== "inward") return url;
let linkArr = url.split("?");
const params = linkArr[1]?.split("&");
if (!params) return linkArr[0];
if (linkArr[0].includes("/")) {
const path = linkArr[0].replace(/^\/+|\/+$/g, "");
const pathNames = path.split("/").filter((it) => it != "");
return [pathNames[0], { screen: pathNames[1] }];
}
const query = params
.map((it) => ({ [it.split("=")[0]]: it.split("=")[1] }))
.reduce((acc, cur) => ({ ...acc, ...cur }), {});
return [linkArr[0], query];
}