一些实用的函数

/**
 * @description: 校验身份证
 * @param {*}
 * @return {*}
 */
export const validateIDCard = value => /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);

/**
 * @description: 校验支付宝账号
 * @param {*}
 * @return {*}
 */
export const validateAlipay = value => /^1\d{10}$|^[a-zA-Z\d._-]*\@[a-zA-Z\d.-]{1,10}\.[a-zA-Z\d]{1,20}$/.test(value);

/**
 * @description: 校验银行卡
 * @param {*}
 * @return {*}
 */
export const validateBankCode = value => /^\d{13,19}$/.test(value);

/**
 * @description: 校验手机号
 * @param {*}
 * @return {*}
 */
export const validatePhone = value => /^1\d{10}$/.test(value);

/**
 * @description: 函数节流
 * @param {*}
 * @return {*}
 */
export const throttle = function (fn, delay = 1000) {
  let prev = 0;
  return function () {
    const now = Date.now();
    if (now - prev > delay) {
      fn.apply(this, arguments);
      prev = Date.now();
    }
  }
}


/**
 * @description: 获取随机字符串
 * @param {*}
 * @return {*}
 */
export const randomString = () => Math.random().toString(36).substr(2);

/**
 * @description: 将 BASE64 转换文件
 * @param {*}
 * @return {*}
 */
export const dataURLtoFile = (dataurl, filename) => {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  if (!filename) filename = `${Date.parse(new Date())}.jpg`;
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

/**
 * @description: 压缩图片
 * @param {*}
 * @return {*}
 */
export const compressImg = file => {
  const fileSize = parseFloat(Number.parseInt(file.size, 10) / 1024 / 1024).toFixed(2);
  const reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise((resolve) => {
    reader.onload = e => {
      const img = new Image();
      img.src = e.target.result;
      img.onload = () => {
        const w = img.width;
        const h = img.height;
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        let base64;
        canvas.setAttribute('width', w);
        canvas.setAttribute('height', h);
        ctx.drawImage(img, 0, 0, w, h);
        if (fileSize <= 1) {
          base64 = canvas.toDataURL(file.type, 1);
        } else if (fileSize <= 3) {
          base64 = canvas.toDataURL(file.type, 0.8);
        } else if (fileSize <= 5) {
          base64 = canvas.toDataURL(file.type, 0.5);
        } else {
          base64 = canvas.toDataURL(file.type, 0.1);
        }
        let fileName = file.name;
        fileName = fileName.replace(/^(.+)\.(.+)$/, (fullName, name, suffix) => name + Math.floor(Math.random() * (9999 - 1000) + 1000) + '.' + suffix);
        resolve(dataURLtoFile(base64, fileName));
      };
    };
  });
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注