index.js 2 KB
export function debounce(fn, delay, triggerNow) {
    var t = null
    console.log('ceshi')
    var debounced = function() {
        var _self = this,
            args = arguments
        if (t) {
            clearTimeout(t)
        }
        if (triggerNow) {
            var exec = !t

            t = setTimeout(function() {
                t = null
            }, delay)

            if (exec) {
                // 初次进来
                fn.apply(_self, args)
            }
        } else {
            t = setTimeout(function() {
                fn.apply(_self, args)
            }, delay)
        }
    }

    debounced.remove = function() {
        clearTimeout(t)
        t = null
    }

    return debounced
}
//格式化日期
export const formatDate = (date, fmt = '-') => {
    //shijianchuo是整数,否则要parseInt转换
    var time = new Date(date)
    var y = time.getFullYear()
    var m = time.getMonth() + 1
    var d = time.getDate()
    var h = time.getHours()
    var mm = time.getMinutes()
    var s = time.getSeconds()
    return y + fmt + add0(m) + fmt + add0(d) + ' ' + add0(h) + ':' + add0(mm)
}

function add0(m) {
    return m < 10 ? '0' + m : m
}

//正则表示式是干什么的? 字符串匹配利器(难,规则多)
export function formatDate2(date, fmt) {
    //1.获取年份
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    //2.获取
    //M+ ->正则表达式一个规则
    //
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
        }
    }
    return fmt
}
//填补左边的零(一般返回字符串最后两位)
function padLeftZero(str) {
    return ('00' + str).substr(str.length)
}