小工具集锦

90 阅读3分钟

小工具集合,欢迎大家在评论区分享,有问题欢迎指正

  1. 获取 url 参数
/**
 * 获取url参数
 * @param name
 * @param url url路径,默认当前路径
 * @return const name = getQueryString('name')
 */
export const getQueryString = (name: string, url = window.location.href) => {
  // 从第一个?开始,且不包括#之后,并截取掉?的部分
  const query = url;
  // 从#开始的部分,并转换成数组
  const hash = url.split('?');
  // query和hash均没有参数
  if (!query && hash.length < 2) {
    return '';
  }
  // 先取query部分的参数进行匹配
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split('=');
    if (pair[0] == name) {
      return pair[1];
    }
  }
  // query没有参数,或者有参数但没找到,则取hash部分的参数
  if (hash.length < 2) {
    return '';
  }
  for (let j = 0; j < hash.length; j++) {
    const = hash[j].split('&');
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split('=');
      if (pair[0] == name) {
        return pair[1];
      }
    }
  }
  return '';
};

2.生成指定长度的随机字符串

/**
 * 生成指定长度的随机字符串
 * @param {Number} length 字符串长度
 * @return 示列: s12asd
 */

export const randomString = (length: any) => {
  // 定义字符串中的字符
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_&*=,';
  let result = '';
  // 循环指定长度
  for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
  // 返回生成的字符串
  return result;
};

3.时间日期格式化(时间戳/标准时间 转时间)

/**
 * 时间格式化
 * @param date Date对象
 * @return 示列: 2022-10-01 10:01:00
 */
export const formatTime = (date: string | number | Date) => {
  if (typeof date === 'string' || typeof date === 'number') {
    // eslint-disable-next-line no-param-reassign
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};

4.千位分隔符

/**
 * 千分号分隔符
 * @param num 需要分割的数字
 * @param decimal 保留小数位
 * @return 示列: 123,412
 */
export const micrometerHandle = (num: number | string, decimal = 0) => {
  if (num === 0) return '-';
  if (!num) return '-';
  // eslint-disable-next-line no-param-reassign
  if (decimal > 0) num = (+num).toFixed(decimal);
  // return (num+'').toLocaleString()
  const res = num.toString().replace(/\d+/, (n) => {
    // 先提取整数部分
    return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => {
      return $1 + ',';
    });
  });
  return res;
};

  1. /n 替换成 br
/**
 * /n 替换成 br
 * @param {String} str 需要替换的字符串
 */
export const formatText = (str: string) => {
  if (str) {
    return str.replace(/\n/g, '<br>');
  } else {
    return str;
  }
};

6.函数防抖

/**
 * 函数防抖
 * @param {Function} fn 函数
 * @param {Number} delay 防抖时间
 * @return const xx = debounce(inputFun,1000);
 */
export const debounce = (fn: Function, delay = 300) => {
  let timerId: any;
  function _executer(...args: any) {
    if (timerId) clearTimeout(timerId);
    timerId = setTimeout(() => {
      fn.call(null, ...args);
    }, delay);
  }
  _executer.cancel = () => clearTimeout(timerId);
  return _executer;
};

7.函数节流

/**
 * 函数防抖
 * @param {Function} fn 函数
 * @param {Number} delay 节流时间
 * @return const xx = throttle(inputFun,1000);
 */
export const throttle = (fn, delay = 100) => {
    // 首先设定一个变量,在没有执行我们的定时器时为null
    const timer = null
    return function() {
        // 当我们发现这个定时器存在时,则表示定时器已经在运行中,需要返回
        if (timer) return
        timer = setTimeout(() => {
                fn.apply(this, arguments)
                timer = null
        }, delay)
    }
}
  1. 图片压缩
/**
 * 图片压缩 借助 compressorjs,请自行下载 npm install compressorjs --save
 * @param {File} image 图片
 * @param {String} backType 需要返回的类型blob、file、base64
 * @param {Number} quality 图片压缩比,数字越小,图片压缩越小
 * @return const compImgFile = await compressorImage(file.file, 'file', 0.4)
 */
export const compressorImage = (image: File, backType: string, quality: number) => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-new
    new Compressor(image, {
      quality: quality || 0.8,
      success(result) {
        if (!backType || backType === 'blob') {
          resolve(result);
        } else if (backType === 'file') {
          const file = new File([result], image.name, { type: image.type });
          resolve(file);
        } else if (backType === 'base64') {
          const reader = new FileReader();
          reader.readAsDataURL(result);
          reader.onload = () => resolve(reader.result);
          reader.onerror = (error) => reject(error);
        }
      },
      error(err) {
        reject(err);
      },
    });
  });
};

9.延时器

/**
 * 延时器
 * @param {String} delay number
 * @return await wait(1000);
 */
export const wait = (delay: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, delay);
  });
};