Util.js JavaScript帮助类

项目中用到的一些JavaScript帮助类

import {  APP_NAME_EN} from '../../service/config/config'
import math from 'mathjs'

//必传参数函数
export function errorFunction(error = "必须传入参数") {
  throw new Error(error);
}

//延迟方法
export function timeout(delay) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        resolve(1)
      } catch (e) {
        reject(0)
      }
    }, delay);
  })
}

//去除数组中空null等
export function arrayRejectNull(arr = []) {
  let arrayNullNum = [];
  arr.forEach((p, index) => {
    if (p === null || p.toString().trim() === "" || p === undefined || (typeof p === "number" ? isNaN(p) : false)) {
      arrayNullNum.push(index)
    }
  });
  arrayNullNum.reverse().forEach(n => {
    arr.splice(n, 1)
  });
  return arr;
}

//格式化时间 型为: 2017-01-01 09:10:02
export function formatTime(date) {
  if (!date) return "";
  if (typeof date === "string") date = date.replace("T", " "); //服务器返回的时间中含有T,部分浏览器解释不正确
  date = new Date(date);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//格式化时间 型为: 2017-01-01
export function formatDate(date) {
  if (!date) return "";
  if (typeof date === "string") date = date.replace("T", " "); //服务器返回的时间中含有T,部分浏览器解释不正确
  date = new Date(date);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  return [year, month, day].map(formatNumber).join('-')
}

//根据月份判断季度
export function getQuarterFromMonth(month) {
  if (!month || month < 0 || month > 12) {
    month = (new Date()).getMonth() + 1;
  }
  if (month > 0 && month <= 3) return {
    zh: "一季度",
    en: 1
  };
  if (month > 3 && month <= 6) return {
    zh: "二季度",
    en: 2
  };
  if (month > 6 && month <= 9) return {
    zh: "三季度",
    en: 3
  };
  if (month > 9 && month <= 12) return {
    zh: "四季度",
    en: 4
  };
}

//将个位数补上0
function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n
}

//格式化时间 型为: 2017年1月1日 9点10分
export function formatZhTime(date) {
  if (!date) return "";
  if (typeof date === "string") date = date.replace("T", " ");
  date = new Date(date);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  return `${year}年${month}月${day}日 ${hour}点${minute}分`
}

//格式化时间 型为: 2017年1月1日
export function formatZhDate(date) {
  if (!date) return "";
  if (typeof date === "string") date = date.replace("T", " ");
  date = new Date(date);
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  return `${year}年${month}月${day}日`
}

//时间差
export function distinctTime(start, end) {
  let pastTime = (Date.parse(new Date(end)) - Date.parse(new Date(start))) / 1000; //转成时间戳
  let hours = parseInt(pastTime / (60 * 60));
  let minutes = parseInt((pastTime - hours * 60 * 60) / 60);
  let time;
  if (hours < 1) {
    time = `${minutes}分钟`
  } else if (minutes === 0) {
    time = `${hours}小时`
  } else {
    time = `${hours}小时${minutes}分钟`
  }
  return time
}

//ISO8601转RFC2822
export function ISO2RFC(date) {
  //date形如 2017-06-18T13:00:00 应将T去掉并且将'-' 替换为'/' 才能使所有的浏览器解析一致
  let newDate = date.toString();
  return newDate.replace('T', ' ').replace(/-/g, '/');
}

//获取某月天数
export function getMonthDay(date) {
  let mdate = new Date(new Date(date).toLocaleDateString());
  mdate.setDate(32); //自动减去当月的天数
  return 32 - mdate.getDate() //date.getDate()会返回一个减去当月天数的值 剩余值就是当月天数
}

//本周的开端日期
export function getWeekStartDate(date) {
  let now = date || new Date(); //当前日期
  let nowDayOfWeek = now.getDay() === 0 ? 7 : now.getDay(); //今天本周的第几天
  let nowDay = now.getDate(); //当前日
  let nowMonth = now.getMonth(); //当前月
  let nowYear = now.getFullYear(); //当前年
  let weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
  return formatDate(weekStartDate);
}

//本周的停止日期
export function getWeekEndDate(date) {
  let now = date || new Date(); //当前日期
  let nowDayOfWeek = now.getDay() === 0 ? 7 : now.getDay(); //今天本周的第几天
  let nowDay = now.getDate(); //当前日
  let nowMonth = now.getMonth(); //当前月
  let nowYear = now.getFullYear(); //当前年
  let weekEndDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek));
  return formatDate(weekEndDate);
}

//桩号显示为小数  如:k200+110 => 200.110
export function formatStakeNumber(value = "") {
  return parseFloat(value.replace('+', '.').replace(/k/ig, '')).toFixed(3);
}

//小数转桩号  如:200.110 => k200+110
export function numberToStake(value) {
  if (!value) return '';
  let floatNum = parseFloat(value);
  if (isNaN(floatNum)) return '';
  let num = (parseFloat(value).toFixed(3) + '').split(".");
  return "K" + num[0] + "+" + num[1];
}

//将0换成空字符
export function zeroToEmpty(value) {
  if ((value + '').trim() === "0" || (value + '').trim() === "") return "";
  return value
}

//store names
export const storeNames = {
  'system_login': APP_NAME_EN + 'jcfjzhglglxt_dl','
};
/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
};
/**
 * 获取localStorage
 */
export const getStore = name => {
  if (!name) return;
  return window.localStorage.getItem(name)
};
/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return;
  window.localStorage.removeItem(name)
};
/**
 * 存储localSessionStorage
 */
export const setSessionStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.sessionStorage.setItem(name, content)
};
/**
 * 获取localSessionStorage
 */
export const getSessionStore = name => {
  if (!name) return;
  return window.sessionStorage.getItem(name)
};
/**
 * 删除localSessionStorage
 */
export const removeSessionStore = name => {
  if (!name) return;
  window.sessionStorage.removeItem(name)
};
/*
 * 对象浅拷贝 数组和对象
 * */
export const copy = object => {
  if (Object.prototype.toString.call(object) === '[object Array]') return object.slice();
  let o = {};
  for (let item in object) {
    if (object.hasOwnProperty(item)) o[item] = object[item];
  }
  return o;
};
/*
 * 对象深拷贝
 * */
export const copyDeep = function (obj) {
  let str, newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object') {
    return;
  } else if (window.JSON) {
    str = JSON.stringify(obj), //序列化对象
      newobj = JSON.parse(str); //还原
  } else {
    for (let i in obj) {
      newobj[i] = typeof obj[i] === 'object' ?
        copyDeep(obj[i]) : obj[i];
    }
  }
  return newobj;
};
/*
 * 取小数点整位数
 * */
export const getNumWithFloat = f => {
  return f.toString().replace(/(\d+)\.(\d*)/, "$1");
};
/*
 * 取小数点后小数位
 * */
export const getDecimalWithFloat = f => {
  return f.toString().replace(/\d+\.(\d*)/, "$1");
};
/**
 * 给定数字和长度,不足位数自动补零
 */
export const prefixInteger = (num, length) => {
  return (Array(length).join('0') + num).slice(-length);
};
/**
 * 不足为补0,超出则舍去后面的值
 */
export const stakePrefix = (num, length = 3) => {
  if ((num + '').length >= length) {
    return (num + '').slice(0, length);
  }
  return prefixInteger(num, length);
};

/**
 * 如果有小数部分,保留n位小数
 **/
export function remainDecimal(float, n = 0) {
  if (float === null || float === undefined || float === "") return "";
  let numStrings = (float + '').split('.');
  if (numStrings.length === 2) {
    return math.round(parseFloat(float), n);
  } else {
    return math.round(float)
  }
}

/**
 * base64 加密解密
 * var result = base.encode("123");
 * var result2 = base.decode(result);
 */
export const Base64 = {
  // private property
  _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
  // public method for encoding
  encode(input) {
    if (!input) return;
    let output = '';
    let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    let i = 0;
    input = this._utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64
      } else if (isNaN(chr3)) {
        enc4 = 64
      }
      output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4)
    }
    return output
  },
  // public method for decoding
  decode(input) {
    if (!input) return;
    let output = '';
    let chr1, chr2, chr3;
    let enc1, enc2, enc3, enc4;
    let i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
    while (i < input.length) {
      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2)
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3)
      }
    }
    output = this._utf8_decode(output);
    return output
  },
  // private method for UTF-8 encoding
  _utf8_encode(string) {
    string = string.replace(/\r\n/g, '\n');
    let utftext = '';
    for (let n = 0; n < string.length; n++) {
      let c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c)
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128)
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128)
      }
    }
    return utftext
  },
  // private method for UTF-8 decoding
  _utf8_decode(utftext) {
    let string = '';
    let i = 0;
    let c = 0;
    let c1 = 0;
    let c2 = 0;
    let c3 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3
      }
    }
    return string
  }
};
//动态加载css js 文件方法
export const dynamicLoading = {
  //监测是否已经加载过
  css: function (path) {
    if (!path || path.length === 0) {
      throw new Error('argument "path" is required !');
    }
    let head = document.getElementsByTagName('head')[0];
    let link = document.createElement('link');
    link.href = path;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    head.appendChild(link);
  },
  js: function (path, async = false) {
    if (!path || path.length === 0) {
      throw new Error('argument "path" is required !');
    }
    return new Promise((resolve, reject) => {
      let head = document.getElementsByTagName('head')[0];
      let script = document.createElement('script');
      script.src = path;
      script.async = async;
      script.charset = 'utf-8';
      script.type = 'text/javascript';
      script.onload = () => {
        resolve();
      };
      script.onerror = () => {
        console.error(path + " is not loaded success.");
        reject(new Error(path + " is not loaded success."))
      };
      head.appendChild(script);
    })
  }
};

//验证电话号码
export function isPhoneNum(num) {
  return /^1[3|4|5|7|8|9][0-9]\d{8}$/.test(num)
}

//防抖
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result
  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp
    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }
    return result
  }
}

/**
 * js 实现 linq groupBy
 *
 * @param {*} array
 * @param {*} f =>item.name || f=>[item.name,item.Average]
 * @returns
 */
export function groupBy(array, f) {
  let groups = {};
  array.forEach(o => {
    let group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(group => groups[group])
}

你可能感兴趣的:(Util.js JavaScript帮助类)