前端工具函数

71 阅读1分钟
  1. 生成uuid
// 生成uuid
function uuid() {
    return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, c => {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}
  1. 获取顶级domain
// 获取顶级domain, 主要是解决cookie跨域访问问题
getCookieDomain = (): string => {
  let host: string = location.hostname;
  let str: string = "";
  const ip = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  if (ip.test(host) === true || host === 'localhost') return `${host}`;
  const regex = /([^]*).*/;
  const match = host.match(regex);
  if (typeof match !== "undefined" && null !== match) str = match[1];
  if (typeof host !== "undefined" && null !== host) {
    const strAry = host.split(".");
    if (strAry.length > 1) {
      if (strAry.length === 2) str = `${host}`;
      if (str.length > 2) {
        str = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1];
      }

    }
    str = str === "com.cn" ? strAry[strAry.length - 3] + "." + str : str;
  }

  return "." + str;
}
  1. 判断类型
// 判断是否为promise
export const isPromise = (ret): boolean => {
  return (ret && typeof ret.then === 'function' && typeof ret.catch === "function");
}
// 判断是否为函数
export function isFunction(param: any) {
  return typeof param === 'function';
}
// 判断是否为字符串
export function isString(param: any) {
  return typeof param === 'string';
}
// 判断是否为对象类型
export function isObject(param: any) {
  return Object.prototype.toString.call(param) === "[object Object]";
}
// 判断是否为错误对象
export function isError(param: any) {
  return Object.prototype.toString.call(param).indexOf('Error') > -1;
}
  1. 生成随机颜色
export const generateRandomHexColor = () =>
  `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;

5.react实现路由懒加载

/**
 * @Author: visupervi
 * @Date: 2020-10-10 09:50
 * @return:
 * @Description 实现路由懒加载
*/
import React, { Component } from "react";
import { withRouter } from "react-router-dom";

export const asyncComponent = (importComponent)=> {
  class AsyncComponent extends Component {
    constructor(props) {
      super(props);

      this.state = {
        component: null
      };
    }

    async componentDidMount() {
      const { default: component } = await importComponent();
      // // console.log("component",component);
      this.setState({
        component: component
      });
    }

    render() {
      const C = this.state.component;
      return C ? <C {...this.props} /> : null;
    }
  }
  return withRouter(AsyncComponent);
};
  1. rem函数
// eslint-disable-next-line no-unused-expressions
!(function (n) {
  let e = n.document,
    t = e.documentElement,
    i = 750,
    d = i / 40,
    o = "orientationchange" in n ? "orientationchange" : "resize",
    a = function () {
      var n = t.clientWidth || 320;
      n > 720 && (n = 750);
      t.style.fontSize = n / d + "px";
    };
  // eslint-disable-next-line no-unused-expressions
  e.addEventListener && (n.addEventListener(o, a, !1), e.addEventListener("DOMContentLoaded", a, !1));

})(window);

7.获取当前月最后一天

// 获取当前月最后一天
export const getCurrentMonthLast = () => {
  let date = new Date();
  let currentMonth = date.getMonth();
  let nextMonth = ++currentMonth;
  let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  let oneDay = 1000 * 60 * 60 * 24;
  let lastTime = new Date(nextMonthFirstDay - oneDay);
  let month = parseInt(lastTime.getMonth() + 1);
  let day = lastTime.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  return date.getFullYear() + '-' + month + '-' + day;
};
  1. 获取当前月的第一天
// 获取当前月的第一天
export const getCurrentMonthFirst = () => {
  let date = new Date();
  date.setDate(1);
  let month = parseInt(date.getMonth() + 1);
  let day = date.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  return date.getFullYear() + '-' + month + '-' + day;
};