前端使用次數(shù)最多的一些實(shí)用工具封裝
1. 數(shù)據(jù)處理工具
1.1 數(shù)組去重并保持順序
- 功能分析:去除數(shù)組中的重復(fù)元素,并保持元素的原始順序。在處理需要保持特定順序的數(shù)據(jù),如用戶操作歷史記錄等場景中很有用。
- 代碼實(shí)現(xiàn):
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 數(shù)組分組
- 功能分析:根據(jù)給定的分組函數(shù),將數(shù)組元素分成不同的組。常用于數(shù)據(jù)統(tǒng)計(jì)、分類展示等場景,比如將訂單按月份分組。
- 代碼實(shí)現(xiàn):
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 獲取元素距離視口頂部的距離
- 功能分析:獲取元素相對(duì)于瀏覽器視口頂部的距離,對(duì)于實(shí)現(xiàn)視口相關(guān)的交互,如元素進(jìn)入視口時(shí)觸發(fā)動(dòng)畫等功能很重要。
- 代碼實(shí)現(xiàn):
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 批量添加事件監(jiān)聽器
- 功能分析:為多個(gè)元素一次性添加相同類型的事件監(jiān)聽器,簡化事件綁定操作,提高代碼效率。適用于批量處理同類元素的交互,如按鈕組的點(diǎn)擊事件。
- 代碼實(shí)現(xiàn):
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. 網(wǎng)絡(luò)請(qǐng)求工具(基于 Axios)
3.1 帶重試機(jī)制的網(wǎng)絡(luò)請(qǐng)求封裝
- 功能分析:在網(wǎng)絡(luò)請(qǐng)求失敗時(shí),自動(dòng)進(jìn)行重試,提高請(qǐng)求的成功率。對(duì)于不穩(wěn)定的網(wǎng)絡(luò)環(huán)境或偶爾出現(xiàn)的短暫故障很實(shí)用。
- 代碼實(shí)現(xiàn):
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請(qǐng)求
httpUtils.get('/api/data', { param1: 'value1' }, 5)
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
4. 存儲(chǔ)管理工具
4.1 本地存儲(chǔ)有效期管理
- 功能分析:為本地存儲(chǔ)的數(shù)據(jù)設(shè)置有效期,過期后自動(dòng)刪除。適用于存儲(chǔ)一些臨時(shí)數(shù)據(jù),如用戶登錄的短期憑證等。
- 代碼實(shí)現(xiàn):
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. 日期時(shí)間處理工具
5.1 獲取指定月份的所有日期
- 功能分析:獲取指定年份和月份的所有日期,在日歷組件開發(fā)等場景中經(jīng)常用到。
- 代碼實(shí)現(xiàn):
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 計(jì)算兩個(gè)日期之間的工作日天數(shù)
- 功能分析:計(jì)算兩個(gè)日期之間的工作日天數(shù),不包括周末。在項(xiàng)目進(jìn)度管理、考勤計(jì)算等場景中有實(shí)際應(yīng)用。
- 代碼實(shí)現(xiàn):
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);
// 計(jì)算2024年10月1日到10月10日之間的工作日天數(shù)
總結(jié)
到此這篇關(guān)于前端使用次數(shù)最多的一些實(shí)用工具封裝的文章就介紹到這了,更多相關(guān)前端工具封裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解通用webpack多頁面自動(dòng)導(dǎo)入方案
本文主要介紹了通用webpack多頁面自動(dòng)導(dǎo)入方案,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
js獲取當(dāng)前年月日時(shí)分秒的方法實(shí)例(new?Date()/moment.js)
JavaScript是一種流行的編程語言,它可以用來獲取當(dāng)前年月日,這篇文章主要給大家介紹了關(guān)于js獲取當(dāng)前年月日時(shí)分秒的相關(guān)資料,分別使用的是new?Date()/moment.js,需要的朋友可以參考下2024-07-07
等待指定時(shí)間后自動(dòng)跳轉(zhuǎn)或關(guān)閉當(dāng)前頁面的js代碼
本文為大家詳細(xì)介紹下如何通過js實(shí)現(xiàn)等待指定時(shí)間后自動(dòng)跳轉(zhuǎn)或關(guān)閉當(dāng)前頁面的腳步代碼,感興趣的朋友可以參考下哈,希望對(duì)大家有所幫助2013-07-07
JavaScript實(shí)現(xiàn)動(dòng)畫打開半透明提示層的方法
這篇文章主要介紹了JavaScript實(shí)現(xiàn)動(dòng)畫打開半透明提示層的方法,涉及javascript操作DOM的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
如何使用big.js解決JavaScript浮點(diǎn)數(shù)精度丟失問題
最近在項(xiàng)目中涉及到金額從元轉(zhuǎn)為分(乘100即可),發(fā)現(xiàn)乘法居然也會(huì)有精度丟失的問題,關(guān)于浮點(diǎn)數(shù)計(jì)算精度丟失是很多語言都存在的問題,本文給大家分享使用big.js解決JavaScript浮點(diǎn)數(shù)精度丟失問題,感興趣的朋友一起看看吧2023-12-12
Bootstrap警告(Alerts)的實(shí)現(xiàn)方法
這篇文章主要為大家詳細(xì)介紹了Bootstrap警告(Alerts)的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
淺析JavaScript訪問對(duì)象屬性和方法及區(qū)別
這篇文章主要介紹了淺析JavaScript訪問對(duì)象屬性和方法及區(qū)別的相關(guān)資料,需要的朋友可以參考下2015-11-11
js實(shí)現(xiàn)精確到秒的倒計(jì)時(shí)效果
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)精確到秒的倒計(jì)時(shí)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05

