index.js 2.54 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) => {
    if (!date) {
      date = new Date();
    }
  
    let o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒  1-3 位  只能一位占位符
      "U+": date.getMilliseconds() //毫秒   可以1-3位占位符
    };
    fmt = fmt || "yyyy-MM-dd hh:mm";
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (let k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
        );
    return fmt;
  };


//正则表示式是干什么的? 字符串匹配利器(难,规则多)
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);
};