1. 数据处理工具
1.1 数组去重并保持顺序
-
功能分析:去除数组中的重复元素,并保持元素的原始顺序。在处理需要保持特定顺序的数据,如用户操作历史记录等场景中很有用。
-
代码实现:
const arrayUtils = {
uniqueArrayPreserveOrder: function <T>(arr: T[]): T[] {
const seen: { [key: string]: boolean } = {};
return arr.filter((item) => {
const key = typeof item === 'object'? JSON.stringify(item) : item;
if (seen[key]) {
return false;
}
seen[key] = true;
return true;
});
}
};
const arrWithDuplicates = [1, { value: 'a' }, 2, { value: 'a' }, 3];
const uniqueArr = arrayUtils.uniqueArrayPreserveOrder(arrWithDuplicates);
console.log(uniqueArr);
// 输出: [1, { value: 'a' }, 2, 3]
1.2 数组分组
-
功能分析:根据给定的分组函数,将数组元素分成不同的组。常用于数据统计、分类展示等场景,比如将订单按月份分组。
-
代码实现:
const arrayUtils = {
groupArray: function <T, K>(arr: T[], keySelector: (item: T) => K): { [key: string]: T[] } {
return arr.reduce((acc, item) => {
const key = keySelector(item).toString();
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {} as { [key: string]: T[] });
}
};
const orders = [
{ id: 1, date: new Date('2024 - 01 - 10'), amount: 100 },
{ id: 2, date: new Date('2024 - 02 - 15'), amount: 200 },
{ id: 3, date: new Date('2024 - 01 - 20'), amount: 150 }
];
const groupedOrders = arrayUtils.groupArray(orders, order => order.date.getMonth());
console.log(groupedOrders);
// 输出: { '0': [ { id: 1, date: 2024 - 01 - 10, amount: 100 }, { id: 3, date: 2024 - 01 - 20, amount: 150 } ], '1': [ { id: 2, date: 2024 - 02 - 15, amount: 200 } ] }
2. DOM 操作工具
2.1 获取元素距离视口顶部的距离
-
功能分析:获取元素相对于浏览器视口顶部的距离,对于实现视口相关的交互,如元素进入视口时触发动画等功能很重要。
-
代码实现:
const domUtils = {
getElementTopRelativeToViewport: function (element: HTMLElement): number {
const rect = element.getBoundingClientRect();
return rect.top + window.pageYOffset;
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>DOM Utils Example</title>
<style>
#testDiv {
margin - top: 200px;
}
</style>
</head>
<body>
<div id="testDiv">Test Div</div>
<script lang="ts">
const testDiv = document.getElementById('testDiv') as HTMLElement;
const divTop = domUtils.getElementTopRelativeToViewport(testDiv);
console.log(divTop);
</script>
</body>
</html>
2.2 批量添加事件监听器
-
功能分析:为多个元素一次性添加相同类型的事件监听器,简化事件绑定操作,提高代码效率。适用于批量处理同类元素的交互,如按钮组的点击事件。
-
代码实现:
const domUtils = {
addEventListeners: function (selector: string, eventType: string, handler: (event: Event) => void) {
const elements = document.querySelectorAll(selector);
elements.forEach((element) => {
element.addEventListener(eventType, handler);
});
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF - 8">
<title>DOM Utils Example</title>
</head>
<body>
<button class="actionButton">Button 1</button>
<button class="actionButton">Button 2</button>
<script lang="ts">
domUtils.addEventListeners('.actionButton', 'click', (event) => {
console.log('Button clicked');
});
</script>
</body>
</html>
3. 网络请求工具(基于 Axios)
3.1 带重试机制的网络请求封装
-
功能分析:在网络请求失败时,自动进行重试,提高请求的成功率。对于不稳定的网络环境或偶尔出现的短暂故障很实用。
-
代码实现:
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
interface ResponseData<T> {
code: number;
message: string;
data: T;
}
const httpUtils: {
instance: AxiosInstance;
init: () => void;
get: <T>(url: string, params?: object, retries = 3): Promise<T>;
post: <T>(url: string, data?: object, retries = 3): Promise<T>;
put: <T>(url: string, data?: object, retries = 3): Promise<T>;
delete: <T>(url: string, retries = 3): Promise<T>;
} = {
instance: axios.create({
baseURL: 'https://your - api - base - url.com',
timeout: 5000,
headers: {
'Content - Type': 'application/json'
}
}),
init: function () {
this.instance.interceptors.request.use((config: AxiosRequestConfig) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, error => {
return Promise.reject(error);
});
this.instance.interceptors.response.use((response: AxiosResponse<ResponseData<any>>) => {
if (response.data.code!== 200) {
throw new Error(response.data.message);
}
return response.data.data;
}, error => {
console.error('Request error:', error);
return Promise.reject(error);
});
},
get: async function <T>(url: string, params: object = {}, retries = 3): Promise<T> {
let attempt = 0;
while (attempt < retries) {
try {
const response = await this.instance.get(url, { params });
return response.data;
} catch (error) {
attempt++;
if (attempt === retries) {
throw error;
}
}
}
throw new Error('Max retries reached');
},
post: async function <T>(url: string, data: object = {}, retries = 3): Promise<T> {
let attempt = 0;
while (attempt < retries) {
try {
const response = await this.instance.post(url, data);
return response.data;
} catch (error) {
attempt++;
if (attempt === retries) {
throw error;
}
}
}
throw new Error('Max retries reached');
},
put: async function <T>(url: string, data: object = {}, retries = 3): Promise<T> {
let attempt = 0;
while (attempt < retries) {
try {
const response = await this.instance.put(url, data);
return response.data;
} catch (error) {
attempt++;
if (attempt === retries) {
throw error;
}
}
}
throw new Error('Max retries reached');
},
delete: async function <T>(url: string, retries = 3): Promise<T> {
let attempt = 0;
while (attempt < retries) {
try {
const response = await this.instance.delete(url);
return response.data;
} catch (error) {
attempt++;
if (attempt === retries) {
throw error;
}
}
}
throw new Error('Max retries reached');
}
};
httpUtils.init();
export default httpUtils;
import httpUtils from './httpUtils';
// GET请求
httpUtils.get('/api/data', { param1: 'value1' }, 5)
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
4. 存储管理工具
4.1 本地存储有效期管理
-
功能分析:为本地存储的数据设置有效期,过期后自动删除。适用于存储一些临时数据,如用户登录的短期凭证等。
-
代码实现:
const storageUtils = {
setLocalStorageWithExpiry: function (key: string, value: any, durationInMinutes: number) {
const data = {
value,
expiry: new Date().getTime() + durationInMinutes * 60 * 1000
};
localStorage.setItem(key, JSON.stringify(data));
},
getLocalStorageWithExpiry: function (key: string): any {
const item = localStorage.getItem(key);
if (!item) {
return null;
}
const { value, expiry } = JSON.parse(item);
if (new Date().getTime() > expiry) {
localStorage.removeItem(key);
return null;
}
return value;
}
};
storageUtils.setLocalStorageWithExpiry('tempToken', 'abc123', 30);
const tempToken = storageUtils.getLocalStorageWithExpiry('tempToken');
console.log(tempToken);
5. 日期时间处理工具
5.1 获取指定月份的所有日期
-
功能分析:获取指定年份和月份的所有日期,在日历组件开发等场景中经常用到。
-
代码实现:
const dateTimeUtils = {
getDatesOfMonth: function (year: number, month: number): Date[] {
const dates: Date[] = [];
const lastDay = new Date(year, month + 1, 0).getDate();
for (let day = 1; day <= lastDay; day++) {
dates.push(new Date(year, month, day));
}
return dates;
}
};
const dates = dateTimeUtils.getDatesOfMonth(2024, 9);
dates.forEach(date => {
console.log(date.toISOString().split('T')[0]);
});
// 输出2024年10月的所有日期
5.2 计算两个日期之间的工作日天数
-
功能分析:计算两个日期之间的工作日天数,不包括周末。在项目进度管理、考勤计算等场景中有实际应用。
-
代码实现:
const dateTimeUtils = {
getWorkingDaysBetween: function (startDate: Date, endDate: Date): number {
let currentDate = new Date(startDate);
let workingDays = 0;
while (currentDate <= endDate) {
const dayOfWeek = currentDate.getDay();
if (dayOfWeek!== 0 && dayOfWeek!== 6) {
workingDays++;
}
currentDate.setDate(currentDate.getDate() + 1);
}
return workingDays;
}
};
const start = new Date('2024 - 10 - 01');
const end = new Date('2024 - 10 - 10');
const workingDays = dateTimeUtils.getWorkingDaysBetween(start, end);
console.log(workingDays);
// 计算2024年10月1日到10月10日之间的工作日天数