javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > 前端工具封装

前端使用次数最多的一些实用工具封装

作者:一支鱼

在前端开发中,封装是实现代码复用、提高可维护性的重要手段,这篇文章主要介绍了前端使用次数最多的一些实用工具封装,文中通过代码介绍的非常详细,需要的朋友可以参考下

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日之间的工作日天数

总结 

到此这篇关于前端使用次数最多的一些实用工具封装的文章就介绍到这了,更多相关前端工具封装内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文