常用工具类函数(不定期更新)

/**
 * @description 加法函数,用来得到精确的加法结果
 * @params {arg1} 加数
 * @params {arg2} 加数
 */
export function Add(arg1, arg2) {
  arg1 = arg1.toString(); arg2 = arg2.toString();
  let arg1Arr = arg1.split("."), arg2Arr = arg2.split("."), d1 = arg1Arr.length == 2
    ? arg1Arr[1]
    : "", d2 = arg2Arr.length === 2 ? arg2Arr[1] : "";
  let maxLen = Math.max(d1.length, d2.length);
  let m = Math.pow(10, maxLen);
  let result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen));
  let d = arguments[2];
  return typeof d === "number" ? Number((result).toFixed(d)) : result;
}
/**
 * @description 减法函数,用来得到精确的减法结果
 * @params {arg1} 被减数
 * @params {arg2} 减数
 */
export function Sub(arg1, arg2) {
  return Add(arg1, -Number(arg2), arguments[2]);
}
/**
 * @description 乘法函数,用来得到精确的乘法结果
 * @params {arg1} 乘数
 * @params {arg2} 乘数
 */
export function Mul(arg1, arg2) {
  let r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
  m = (r1.split(".")[1] ? r1.split(".")[1].length : 0)
    + (r2.split(".")[1] ? r2.split(".")[1].length : 0);
  resultVal = Number(r1.replace(".", ""))
    * Number(r2.replace(".", "")) / Math.pow(10, m);
  return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
}
/**
 * @description 除法函数,用来得到精确的除法结果
 * @params {arg1} 除数
 * @params {arg2} 被除数
 */
export function Div(arg1, arg2) {
  let r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
  m = (r2.split(".")[1] ? r2.split(".")[1].length : 0)
    - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
  resultVal = Number(r1.replace(".", ""))
    / Number(r2.replace(".", "")) * Math.pow(10, m);
  return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
}
/**
 * @description 日期格式化函数
 * @params {millionsTime} 毫秒级时间戳
 * @params {pattern} 需求格式
 */
export function dateFormat(millionsTime, pattern = 'yyyy-MM-dd hh:mm:ss'){
  let d = new Date();
  d.setTime(millionsTime);
  let date = {
    "M+": d.getMonth() + 1,
    "d+": d.getDate(),
    "h+": d.getHours(),
    "m+": d.getMinutes(),
    "s+": d.getSeconds(),
    "q+": Math.floor((d.getMonth() + 3) / 3),
    "S+": d.getMilliseconds()
  };
  if (/(y+)/i.test(pattern)) {
    pattern = pattern.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in date) {
    if (new RegExp("(" + k + ")").test(pattern)) {
      pattern = pattern.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length)
      );
    }
  }
  return pattern;
}
/**
 * @description 获取指定日期是当前年第几周
 * @params {year, month, day} 代表年、月、日的数字
 * @params {firstDayOfWeek} 一周的起始日,1代表周一为一周的第一天,7代表周日为一周的第一天
 *
 */
export function getWeekNumber({year, month, day}, firstDayOfWeek){
  let date1 = new Date(year, parseInt(month) - 1, day);
  let date2 = new Date(year, 0, 1);
  let d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
  return Math.ceil((d + ((date2.getDay() + firstDayOfWeek) - 1)) / 7);
}
/**
 * @description 深克隆函数
 * @params {obj} 需要进行深克隆的数据
 */
export function deepClone(obj){
  let result = obj;
  if(typeof obj === 'object' && obj !== null) {
    result = Object.prototype.toString.call(obj) === '[object Array]' ? [] : {};
    for(let prop in obj) {
      result[prop] = deepClone(obj[prop]);
    }
  }
  return result;
}
/**
 * @description 去除树形数据中子集为空的函数
 * @params {array} 树形数据数组
 * @params {props} 子集 key 值
 */
export function deleteEmptyArrayOfTreeData(array = [], props = 'children'){
  array.map(item => {
    if(item[props] && item[props].length > 0){
      deleteEmptyArrayOfTreeData(item[props], props)
    }else {
      delete item[props]
    }
  });
  return array;
}
/**
 * @description 数组根据某个字段去重函数
 * @params {array} 需要去重的数组
 * @params {key} 去重的字段 key
 */
export function duplicateRemovalByKey(array, key){
  let hash = {};
  array = array.reduce((arr, current) => {
    hash[current[key]] ? "" : (hash[current[key]] = true && arr.push(current));
    return arr;
  }, []);
  return array;
}
/**
 * @description 冒泡排序函数
 * @params {array} 需要排序的数组
 */
export function bubbleSort(array){
  let len = array.length;
  for(let i = 0; i < len - 1; i++) {
    for(let j = 0; j < len - 1 - i; j++) {
      if(array[j] > array[j + 1]){
        let temp = array[j + 1];
        array[j + 1] = array[j];
        array[j] = temp;
      }
    }
  }
  return array;
}
/**
 * @description 数字格式化(千分分隔符)函数
 * @params {num} 需要格式化的数字、或者数字字符串
 * @params {d} 需要保留的小数位数
 */
export function moneyFormat(num = 0, d = 2){
  return (Number(num).toFixed(d).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'))
}
/**
 * @description 判断数据类型的函数
 * @params {data} 需要判断数据类型的数据
 */
export function dataTypeDetection(data){
  return Object.prototype.toString.call(data).replace(/^\[object (\S+)]$/, '$1')
}
/**
 * @description 下划线转驼峰函数
 * @params {key} 需要转换的字段 key
 */
export function underlineToHump(key) {
  return key.replace(/_(\w)/g, function(all, letter){
    return letter.toUpperCase();
  });
}
/**
 * @description 驼峰转下划线函数
 * @params {key} 需要转换的字段 key
 */
export function humpToUnderline(key) {
  return key.replace(/([A-Z])/g,"_$1").toLowerCase();
}
/**
 * @description 金额大写函数
 * @params {key} 需要转换的数字
 */
export function transCnMoney(number){
  let CN_MONEY = "";
  let CN_UNIT = '仟佰拾亿仟佰拾万仟佰拾元角分';
  if(Object.prototype.toString.call(number).replace(/^\[object (\S+)]$/, '$1') === 'String' && number.search(',') > 0)
    number = number.split(',').join('');
  number += "00";
  let dot = number.indexOf('.');
  if (dot >= 0)
    number = number.substring(0, dot) + number.substr(dot + 1, 2);
  CN_UNIT = CN_UNIT.substr(CN_UNIT.length - number.length);
  for (let i = 0; i < number.length; i++)
    CN_MONEY += '零壹贰叁肆伍陆柒捌玖'.substr(number.substr(i, 1), 1) + CN_UNIT.substr(i, 1);
  return CN_MONEY
    .replace(/零角零分$/, '整')
    .replace(/零[仟佰拾]/g, '零')
    .replace(/零{2,}/g, '零')
    .replace(/零([亿|万])/g, '$1')
    .replace(/零+元/, '元')
    .replace(/亿零{0,3}万/, '亿')
    .replace(/^元/, "零元");
}
/**
 * @description 根据URI下载文件(非email格式文件)
 * @params {fileUrl} 文件路径
 * @params {fileName} 文件名
 */
export function fileDownLoad(fileUrl, fileName) {
  let aElement = document.createElement("a");
  aElement.download = fileName ? fileName : '';
  aElement.style.display = 'none';
  aElement.href = fileUrl;
  document.body.appendChild(aElement);
  aElement.click();
  document.body.removeChild(aElement)
}
/**
 * @description 设置 el 表头宽度函数
 * @params {str} 表头 label 字符串
 * @params {minWidth} 最小宽度,默认120px
 */
export function flexColumnWidth(str, minWidth = 120) {
  let flexWidth = 0;
  for (const char of str) {
    if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
      // 如果是英文字符,为字符分配10个单位宽度,单位宽度可根据字体大小调整
      flexWidth += 10
    } else if (char >= '\u4e00' && char <= '\u9fa5') {
      // 如果是中文字符,为字符分配14个单位宽度,单位宽度可根据字体大小调整
      flexWidth += 14
    } else {
      // 其他种类字符,为字符分配10个单位宽度,单位宽度可根据字体大小调整
      flexWidth += 10
    }
  }
  if (flexWidth < minWidth) {
    // 设置最小宽度
    flexWidth = minWidth
  }
  return flexWidth + 'px'
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值