"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.retry = exports.throttle = exports.toHexStr = exports.delay = void 0;
/**
 * 延迟
 */
function delay(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}
exports.delay = delay;
/**
 * 转16进制字符串
 * @param limit 转换长度限制
 */
function toHexStr(data, limit) {
    const arr = [];
    limit = limit && limit > 0 && limit < data.length ? limit : data.length;
    for (let i = 0; i < limit; i++) {
        arr.push(data[i].toString(16).padStart(2, "0"));
    }
    return arr.join(" ");
}
exports.toHexStr = toHexStr;
/**
 * 节流器
 *
 * 单位时间内只执行一次
 * @param limit 单位时间(毫秒)
 */
function throttle(fn, limit) {
    let wait = false;
    return function () {
        if (wait === false) {
            wait = true;
            setTimeout(function () {
                wait = false;
            }, limit);
            fn.apply(this, arguments);
        }
    };
}
exports.throttle = throttle;
/**
 * 重试器
 * @param maxAttempts 最大重试次数
 * @param delay 每次重试延迟时间(毫秒)
 */
function retry(fn, maxAttempts = 1, delay = 1000) {
    return new Promise((resolve, reject) => {
        const attempt = (currentAttempt) => {
            fn()
                .then(resolve)
                .catch((err) => {
                if (currentAttempt < maxAttempts) {
                    setTimeout(() => attempt(currentAttempt + 1), delay);
                }
                else {
                    reject(err);
                }
            });
        };
        attempt(1);
    });
}
exports.retry = retry;
