【Utils】那些常用的JavaScript工具函数(一)

1,990 阅读2分钟

这是我参与更文挑战的第 15 天,活动详情查看: 更文挑战

前文分别介绍了【专栏-效率工具】系列的各个工具,【效率工具】优化开发环境【接口调试工具-Insomnia(一)】...-,- 介绍了【效率工具】,接下来就是技术文了:codings,持续更新、记录 仅当参考,按需食用,不足之处,欢迎各路大佬不吝赐教,补充完善,欢迎分享

  • 工欲善其事,必先利其器。实践(巧偷懒)促进科技发展-,-

  • 本文及后续更文将为大家分享日常开发用到的一些工具函数,总结的样式,代码规范(CodeStyle),代码段等。为迅速 follow 团队的开发规范,快速融入到项目开发中,提高我们的工作效率,减少累赘代码,提高代码质量,减少bug.

  • 这里分享一些代码段: js-utils

js-utils

1. 获取 JS 数据类型

1.1 一行搞定(大写字母开头)

/**
 * 获取 JS 数据类型 返回大写字母开头
 * @param data
 * @returns {string} Function | Array | String | Number | Undefined | Null...
 */
export const getType = (data: any) => {
  return Object.prototype.toString.call(data).slice(8, -1)
}

1.2 处理一下,使用时更简单(纯小写)

/**
 * 获取 JS 基本数据类型, 返回小写字母开头
 * @param data
 * @returns {string} array | string | number ...
 */
const getType = (data: any) => {
  const type = Object.prototype.toString.call(data).split(' ')[1]
  return type.substring(0, type.length - 1).toLowerCase()
}

2. 获取 UUID

/**
 * 获取一串不会重复的字符(UUID)
 * @returns uuid {string}
 */
export const getUuid = () => {
  return Number(Math.random().toString().substr(2, 5) + Date.now()).toString(36)
}

3. 金钱格式化

/**
 * 格式化金钱
 *
 * @export
 * @param {Number|String} number
 * @param {string} [currency="cny"] - 任何有效的ISO 4217 currency code均可, 比如人民币"cny"(默认),韩币'krw',日元'jpy'
 * @returns {String}
 */
export const formatMoney = (number, currency = "cny") => {
  return (
    (
      (number || number === 0) &&
      !isNaN(Number(number)) &&
      Number(number)
    ).toLocaleString("zh", {
      style: "currency",
      currency
    }) || "-"
  );
}

4. 时间格式处理

现推荐 day.js: Day.js 中文网, 原项目使用 moment.js

/**
 * TimeHelper 时间处理
 */
export default class TimeHelper {
  private static zerofill(n: number) {
    return n < 10 ? `0${n}` : n
  }

  static getYyyyMmDd(now: number = Date.now()) {
    const _now: Date = new Date(now)
    const yyyy = _now.getFullYear()
    const MM = _now.getMonth() + 1
    const DD = _now.getDate()
    return `${yyyy}${this.zerofill(MM)}${this.zerofill(DD)}`
  }

  static formatTimestamp(now: number = Date.now()) {
    const _now: Date = new Date(now)
    const YYYY = _now.getFullYear()
    const MM = _now.getMonth() + 1
    const DD = _now.getDate()
    const hh = _now.getHours()
    const mm = _now.getMinutes()
    const ss = _now.getSeconds()
    return `${YYYY}-${this.zerofill(MM)}-${this.zerofill(DD)} ${this.zerofill(hh)}:${this.zerofill(
      mm
    )}:${this.zerofill(ss)}`
  }
}

2. 实用 正则

2.1 项目中常用的几个正则,后续继续更新、补充

/**
 * 1. 手机号
 * 2. 邮箱后缀
 * 3. 邮箱
 * 4. 文本
 * 5. 数字
 */
const regexp = {
  chinaMobilePhone:
    /^(\+)?(0|86|17951)?(13[0-9]||14[57]||15[012356789]||16[6]||17[678]||18[0-9]||19[89])[0-9]{8}$/,
  mailSuffix: /@[0-9a-z]+\.[0-9a-z]+$/,
  email: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
  text: /^[0-9a-zA-Z\u4e00-\u9fa5\s]*$/,
  number: /^[0-9]*$/,
}
export default regexp

3. 工具封装

3.1 Axios 封装

发起请求之前的拦截器(前置拦截) && 响应拦截器

import Axios from 'axios'
import { ElMessage } from 'element-plus'

const baseURL = 'https://api.github.com'

const axios = Axios.create({
  baseURL,
  timeout: 300000, // request timeout 请求超时 5m
})

// 发起请求之前的拦截器(前置拦截)
axios.interceptors.request.use(
  (config) => {
    // 如果有token 就携带 token
    const token = window.localStorage.getItem('accessToken')

    if (token) {
      config.headers.common.Authorization = token
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response && error.response.data) {
      const code = error.response.status
      const msg = error.response.data.message
      ElMessage.error(`Code: ${code}, Message: ${msg}`)
      console.error(`[Error] `, error.response)
    } else {
      ElMessage.error(`${error}`)
    }

    return error.response
  }
)

export default axios

3.2 基于 iview 的全局 Notice

import { Notice } from 'iview';

export function notice(options) {
  const {
    type = 'info',
    title = '',
    desc,
    duration = 3,
    render,
    name,
    onClose,
  } =
    options || {};

  const config = {
    title: typeof title === 'string' ? title : '',
    render,
    desc,
    duration,
    name,
    onClose,
  };

  return Notice[type] && Notice[type](config);
}

export function closeNotice(name) {
  if (!name) {
    return;
  }
  Notice.close(name);
}

3.3 基于 iview 的全局 Message

import { Message } from 'iview';

export function message(
  type = 'info',
  msg = '',
  duration = 3,
  closable = false
) {
  const config = {
    content:
      typeof msg === 'string'
        ? msg
        : typeof msg === 'function'
          ? undefined
          : typeof msg === 'object' && msg.message
            ? msg.message
            : '',
    render:
      typeof msg === 'string'
        ? undefined
        : typeof msg === 'function'
          ? msg
          : () => '',
    duration,
    closable,
  };
  return Message[type] && Message[type](config);
}
export default message;

这里列举部分仅作参考,抛砖引玉,

有没有 get 到呢?

欢迎各路大神评论出你的私藏工具, 把你的好用实用的 分享给大家=,=

今日份预告:

继续更新 分享一些积累的 codes/utils/components/styles等等吧

下一篇敬请期待! hahah~