/**
 * 比较常用的工具模块
 * @date 2022-03
 * @author 何华东
 */

import { v4 as uuidv4 } from 'uuid';

/**
 * 延迟
 */
export function delay(ms?: number): Promise<void> {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

/**
 * 替换所有字符串
 * 
 * 不支持替换\\n
 */
export function replaceAll(value: string, searchValue: string, replaceValue: string) {
    if (!value || !searchValue || !replaceValue) return value;

    //replace(/'/g, "/'");
    return value.replace(new RegExp(searchValue, 'g'), replaceValue);
}

/**
 * uuidv4
 */
export function uuid() {
    return uuidv4();
}

/**
 * 拦截对象方法的调用
 * @param handler Reflect.apply(target, thisArg, argArray);
 */
export function interceptMethodCall(obj: object, handler: (target, thisArg, argArray) => any) {
    return new Proxy(obj, {
        get(target, p, receiver) {
            if (typeof target[p] !== 'function')
                return Reflect.get(target, p, receiver);

            return new Proxy(target[p], {
                apply: handler
            });
        }
    });
}