index.js 1.43 KB
export function debounce(fn, delay, triggerNow) {
  var t = null;

  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 function formatDate(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);
};