CMVR-BID/src/utils/fn.js

95 lines
2.6 KiB
JavaScript
Raw Normal View History

2025-08-21 14:11:58 +08:00
/**
* 防抖函数(在指定时间内,如果事件被频繁触发,则只有在最后一次触发后指定的时间间隔内没有再次触发时,才执行函数)
*/
export function debounce(func, delay) {
let timer; // 用于存储定时器的标识符
return function (...args) {
// 每次触发事件时,清除之前的定时器
clearTimeout(timer);
// 设置新的定时器
timer = setTimeout(() => {
func.apply(this, args); // 执行目标函数
}, delay);
};
}
/**
* 节流函数(在指定时间内,无论事件触发多少次,只执行一次函数)
*/
export function throttle(func, limit) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
/*
* 找出两个对象之间的不同点
* */
export function findDifferences(oldData, newData) {
// 创建一个结果对象来存储不同的键值对
const differences = {};
// 获取两个对象的所有键
const keys = new Set([...Object.keys(oldData), ...Object.keys(newData)]);
// 遍历所有键
keys.forEach((key) => {
// 检查两个对象中该键的值是否不同
if (oldData[key] !== newData[key]) {
differences[key] = newData[key];
}
});
return differences;
}
/*
* 将对象中的数值转换为字符串
* */
export function convertNumbersToStringAndRemoveNulls(obj) {
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
// 如果值为 null,跳过该属性
if (value === null) {
continue;
}
// 检查值是否为数字
if (typeof value === 'number') {
result[key] = value.toString();
} else {
result[key] = value;
}
}
}
return result;
}
/*
* 参数编码拼接
* */
export function appendParamsToPath(path, params) {
// 创建一个 URLSearchParams 对象
const searchParams = new URLSearchParams();
// 遍历参数对象,将每个键值对添加到 URLSearchParams 中
for (const key in params) {
if (params.hasOwnProperty(key)) {
const value = params[key];
// 对值进行编码
searchParams.append(key, encodeURIComponent(value));
}
}
// 将查询字符串拼接到路径后面
const queryString = searchParams.toString();
return `${path}?${queryString}`;
}