如何写工具类方法划分脚本

wen 实用脚本 27

本文目录导读:

如何写工具类方法划分脚本

  1. 基本结构设计
  2. 按功能划分的示例
  3. 完整的大型工具类划分示例
  4. 使用示例
  5. 最佳实践建议

我来详细说明如何编写工具类方法划分脚本,包括最佳实践和完整示例。

基本结构设计

基础工具类模板

class UtilityMethods {
    constructor() {
        // 初始化配置
        this.config = {
            debug: false,
            cache: new Map()
        };
    }
    // 静态方法工具类
    static StringUtils = {
        // 字符串方法
        trim(str) {
            return str ? str.trim() : '';
        },
        truncate(str, length) {
            if (!str) return '';
            return str.length > length ? str.substring(0, length) + '...' : str;
        }
    };
    // 实例方法
    formatDate(date, format = 'YYYY-MM-DD') {
        // 日期格式化逻辑
    }
}

按功能划分的示例

日期工具类

// date-utils.js
export class DateUtils {
    static format(date, format = 'YYYY-MM-DD') {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day);
    }
    static isLeapYear(year) {
        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    }
    static getDaysBetween(date1, date2) {
        const d1 = new Date(date1);
        const d2 = new Date(date2);
        const diffTime = Math.abs(d2 - d1);
        return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    }
}

数组工具类

// array-utils.js
export class ArrayUtils {
    static chunk(array, size) {
        const result = [];
        for (let i = 0; i < array.length; i += size) {
            result.push(array.slice(i, i + size));
        }
        return result;
    }
    static unique(array, key = null) {
        if (!key) return [...new Set(array)];
        const seen = new Set();
        return array.filter(item => {
            const value = item[key];
            if (seen.has(value)) return false;
            seen.add(value);
            return true;
        });
    }
    static shuffle(array) {
        const result = [...array];
        for (let i = result.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [result[i], result[j]] = [result[j], result[i]];
        }
        return result;
    }
}

验证工具类

// validation-utils.js
export class ValidationUtils {
    static isEmail(email) {
        const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return regex.test(email);
    }
    static isPhone(phone) {
        const regex = /^1[3-9]\d{9}$/;
        return regex.test(phone);
    }
    static isURL(url) {
        try {
            new URL(url);
            return true;
        } catch {
            return false;
        }
    }
    static isChineseID(id) {
        // 18位身份证验证
        const regex = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
        return regex.test(id);
    }
}

完整的大型工具类划分示例

// utils/index.js
class UtilityScript {
    constructor(options = {}) {
        this.options = {
            debug: false,
            ...options
        };
        this.init();
    }
    init() {
        console.log('Utility script initialized');
    }
    // ==================== 字符串处理 ====================
    string = {
        capitalize: (str) => {
            return str.charAt(0).toUpperCase() + str.slice(1);
        },
        camelCase: (str) => {
            return str.replace(/[_-]\w/g, match => match[1].toUpperCase());
        },
        slugify: (str) => {
            return str
                .toLowerCase()
                .trim()
                .replace(/[^\w\s-]/g, '')
                .replace(/[\s_]+/g, '-')
                .replace(/-+/g, '-');
        }
    };
    // ==================== 数字处理 ====================
    number = {
        format: (num, decimals = 2) => {
            return Number(num).toFixed(decimals);
        },
        toChinese: (num) => {
            const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
            // 简化实现
            return String(num).split('').map(d => digits[parseInt(d)]).join('');
        },
        random: (min, max) => {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    };
    // ==================== 集合操作 ====================
    collection = {
        groupBy: (array, key) => {
            return array.reduce((result, item) => {
                const groupKey = typeof key === 'function' ? key(item) : item[key];
                (result[groupKey] = result[groupKey] || []).push(item);
                return result;
            }, {});
        },
        sortBy: (array, field, order = 'asc') => {
            return [...array].sort((a, b) => {
                const valueA = a[field];
                const valueB = b[field];
                return order === 'asc' ? valueA - valueB : valueB - valueA;
            });
        },
        deepClone: (obj) => {
            return JSON.parse(JSON.stringify(obj));
        }
    };
    // ==================== 文件操作 ====================
    file = {
        getExtension: (filename) => {
            return filename.split('.').pop().toLowerCase();
        },
        formatSize: (bytes) => {
            const units = ['B', 'KB', 'MB', 'GB'];
            let size = bytes;
            let unitIndex = 0;
            while (size >= 1024 && unitIndex < units.length - 1) {
                size /= 1024;
                unitIndex++;
            }
            return `${size.toFixed(2)} ${units[unitIndex]}`;
        },
        generateFileName: (prefix = 'file') => {
            const timestamp = Date.now();
            const random = Math.random().toString(36).substring(2, 8);
            return `${prefix}_${timestamp}_${random}`;
        }
    };
    // ==================== 错误处理 ====================
    error = {
        tryCatch: async (fn, errorHandler = null) => {
            try {
                return await fn();
            } catch (error) {
                if (errorHandler) {
                    return errorHandler(error);
                }
                console.error('Error caught:', error);
                return null;
            }
        },
        createError: (message, code = 'UNKNOWN_ERROR') => {
            const error = new Error(message);
            error.code = code;
            return error;
        }
    };
}
// 导出单例
export default new UtilityScript();
// 导出类以便自定义
export { UtilityScript };

使用示例

// 使用示例
import utils from './utils/index.js';
// 字符串处理
console.log(utils.string.capitalize('hello')); // Hello
console.log(utils.string.slugify('Hello World')); // hello-world
// 数字处理
console.log(utils.number.format(1234.5678, 2)); // 1234.57
console.log(utils.number.random(1, 100)); // 随机数
// 集合操作
const data = [
    { category: 'A', value: 10 },
    { category: 'B', value: 20 },
    { category: 'A', value: 30 }
];
console.log(utils.collection.groupBy(data, 'category'));
// 文件操作
console.log(utils.file.getExtension('document.pdf')); // pdf
console.log(utils.file.formatSize(1048576)); // 1.00 MB
// 错误处理
await utils.error.tryCatch(
    async () => {
        // 可能抛出错误的代码
        throw new Error('出错了');
    },
    (error) => {
        console.log('自定义错误处理:', error.message);
    }
);

最佳实践建议

命名规范

// 好的命名
- formatDate()
- validateEmail()
- parseJSON()
// 避免的命名
- doSomething()
- process()
- handle()

文档注释

/**
 * 格式化日期
 * @param {Date|string} date - 日期对象或字符串
 * @param {string} format - 格式模板 (YYYY-MM-DD)
 * @returns {string} 格式化后的日期字符串
 */
formatDate(date, format) {
    // 实现
}

单元测试

// utils.test.js
describe('StringUtils', () => {
    test('capitalize should capitalize first letter', () => {
        expect(utils.string.capitalize('hello')).toBe('Hello');
    });
    test('slugify should create URL-friendly string', () => {
        expect(utils.string.slugify('Hello World')).toBe('hello-world');
    });
});

这样的工具类划分清晰、维护方便,可以根据项目需求灵活扩展。

抱歉,评论功能暂时关闭!