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

1. 数据处理工具

1.1 数组去重并保持顺序

  • 功能分析:去除数组中的重复元素,并保持元素的原始顺序。在处理需要保持特定顺序的数据,如用户操作历史记录等场景中很有用。
  • 代码实现
ts 复制代码
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;
        });
    }
};
  • 使用示例
ts 复制代码
const arrWithDuplicates = [1, { value: 'a' }, 2, { value: 'a' }, 3];
const uniqueArr = arrayUtils.uniqueArrayPreserveOrder(arrWithDuplicates);
console.log(uniqueArr); 
// 输出: [1, { value: 'a' }, 2, 3]

1.2 数组分组

  • 功能分析:根据给定的分组函数,将数组元素分成不同的组。常用于数据统计、分类展示等场景,比如将订单按月份分组。
  • 代码实现
ts 复制代码
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[] });
    }
};
  • 使用示例
ts 复制代码
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 获取元素距离视口顶部的距离

  • 功能分析:获取元素相对于浏览器视口顶部的距离,对于实现视口相关的交互,如元素进入视口时触发动画等功能很重要。
  • 代码实现
ts 复制代码
const domUtils = {
    getElementTopRelativeToViewport: function (element: HTMLElement): number {
        const rect = element.getBoundingClientRect();
        return rect.top + window.pageYOffset;
    }
};
  • 使用示例
html 复制代码
<!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 批量添加事件监听器

  • 功能分析:为多个元素一次性添加相同类型的事件监听器,简化事件绑定操作,提高代码效率。适用于批量处理同类元素的交互,如按钮组的点击事件。
  • 代码实现
ts 复制代码
const domUtils = {
    addEventListeners: function (selector: string, eventType: string, handler: (event: Event) => void) {
        const elements = document.querySelectorAll(selector);
        elements.forEach((element) => {
            element.addEventListener(eventType, handler);
        });
    }
};
  • 使用示例
html 复制代码
<!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 带重试机制的网络请求封装

  • 功能分析:在网络请求失败时,自动进行重试,提高请求的成功率。对于不稳定的网络环境或偶尔出现的短暂故障很实用。
  • 代码实现
ts 复制代码
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;
  • 使用示例
ts 复制代码
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 本地存储有效期管理

  • 功能分析:为本地存储的数据设置有效期,过期后自动删除。适用于存储一些临时数据,如用户登录的短期凭证等。
  • 代码实现
ts 复制代码
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;
    }
};
  • 使用示例
ts 复制代码
storageUtils.setLocalStorageWithExpiry('tempToken', 'abc123', 30); 
const tempToken = storageUtils.getLocalStorageWithExpiry('tempToken');
console.log(tempToken); 

5. 日期时间处理工具

5.1 获取指定月份的所有日期

  • 功能分析:获取指定年份和月份的所有日期,在日历组件开发等场景中经常用到。
  • 代码实现
ts 复制代码
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;
    }
};
  • 使用示例
ts 复制代码
const dates = dateTimeUtils.getDatesOfMonth(2024, 9); 
dates.forEach(date => {
    console.log(date.toISOString().split('T')[0]);
});
// 输出2024年10月的所有日期

5.2 计算两个日期之间的工作日天数

  • 功能分析:计算两个日期之间的工作日天数,不包括周末。在项目进度管理、考勤计算等场景中有实际应用。
  • 代码实现
ts 复制代码
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;
    }
};
  • 使用示例
ts 复制代码
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日之间的工作日天数
相关推荐
Song5591 天前
elpis框架抽离并发布 SDK-NPM 包
前端
Mintopia1 天前
低代码平台如何集成 AIGC 技术?核心技术衔接点解析
前端·javascript·aigc
Mintopia1 天前
Next.js + AI-SDK + DeepSeek:3 分钟建设属于你的 AI 问答 Demo
前端·javascript·next.js
anyup1 天前
历时 10 天+,速度提升 20 倍,新文档正式上线!uView Pro 开源组件库体验再升级!
前端·typescript·uni-app
_AaronWong2 天前
仿 ElementPlus 的函数式弹窗调用
前端·element
用户21411832636022 天前
AI 当 “牛马”!免费云服务器 + 开源插件,7×24 小时写小说,一晚交出 70 章长篇
前端
IT_陈寒2 天前
React 18新特性全解析:这5个隐藏API让你的性能飙升200%!
前端·人工智能·后端
朦胧之2 天前
【NestJS】项目调试
前端·node.js
!win !2 天前
不定高元素动画实现方案(中)
前端·动画
xw52 天前
不定高元素动画实现方案(中)
前端·css