多维对象转一维对象

let util = {};
// 对象扁平化处理
util.objectFlat = function (obj) {
    let res = {};
    let res2 = {};
    Object.keys(obj).forEach((i) => {
        if (obj[i] instanceof Object) {
            res2 = objectFlat(obj[i]);
        } else {
            res[i] = obj[i];
        }
    });
    return {
        ...res,
        ...res2,
    };
};
// 防抖立即执行
util.debounceRightnow = function (fun, delay = 300) {
    let timeout;
    return function () {
        let context = this;
        let args = [...arguments];
        if (!timeout) {
            fun.apply(context, args);
        } else {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
            timeout = null;
        }, delay);
    };
};
// 截流函数
util.throttle = (func, wait, mustRun) => {
    let timeout;
    let startTime = new Date();

    return function(...args) {
        let context = this;
        let curTime = new Date();

        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔,触发 handler
        if (curTime - startTime >= mustRun) {
            func.apply(context, args);
            startTime = curTime;
            // 没达到触发间隔,重新设定定时器
        } else {
            timeout = setTimeout(func, wait);
        }
    };
};

// 防抖函数
util.debounce = function (fn, ms = 300) {
    let timer = null;
    return function (...arg) {
        timer && clearTimeout(timer);
        timer = setTimeout(() => {
            fn.call(this, ...arg);
        }, ms);
    };
};
// 数组以值为key及value转换为对象
util.array2object = (array) =>
    array.reduce((obj, item) => {
        obj[item] = item;
        return obj;
    }, {});
// 生成base74
function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png"); // 可选其他值 image/jpeg
    return dataURL;
}

// 创建image实例 然后返回base64
image.createBase64Image = function (src, cb) {
    var image = new Image();
    image.src = src + "?v=" + Math.random(); // 处理缓存
    image.crossOrigin = "*"; // 支持跨域图片
    image.onload = function () {
        var base64 = getBase64Image(image);
        cb && cb(base64);
    };
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值