/**
 * 字符串工具函数库
 * 提供对字符串常见处理的常用工具函数。
 */

/**
 * 检查字符串是否为空或仅包含空格
 */
export const isEmptyOrWhitespace = (str: string): boolean => {
    return !str || str.trim().length === 0;
};

/**
 * 将字符串的首字母大写
 */
export const capitalize = (str: string): string => {
    if (!str) return '';
    return str.charAt(0).toUpperCase() + str.slice(1);
};

/**
 * 转换成驼峰命名法 (camelCase)
 */
export const toCamelCase = (str: string): string => {
    return str
        .toLowerCase()
        .replace(/[-_ ]+(\w)/g, (_, group: string) => group.toUpperCase());
};

/**
 * 转换成蛇形命名法 (snake_case)
 */
export const toSnakeCase = (str: string): string => {
    return str
        .replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
        .replace(/[\s\-]+/g, '_')
        .replace(/^_/, '')
        .toLowerCase();
};

/**
 * 转换成烤串命名法 (kebab-case)
 */
export const toKebabCase = (str: string): string => {
    return str
        .replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)
        .replace(/[\s_]+/g, '-')
        .replace(/^-/, '')
        .toLowerCase();
};

/**
 * 截断字符串到指定长度，超出部分使用 "..." 表示
 */
export const truncate = (str: string, length: number): string => {
    if (str.length <= length) return str;
    return str.slice(0, length) + '...';
};

/**
 * 统计字符串中每个字符的出现次数
 */
export const charFrequency = (str: string): Record<string, number> => {
    return str.split('').reduce((acc: Record<string, number>, char: string) => {
        acc[char] = (acc[char] || 0) + 1;
        return acc;
    }, {});
};

/**
 * 检查字符串是否是有效的 JSON
 */
export const isValidJSON = (str: string): boolean => {
    try {
        JSON.parse(str);
        return true;
    } catch {
        return false;
    }
};