本文最后更新于 2025-02-27,文章内容可能已经过时。

随机生成16进制颜色

console.log("#" + Math.random().toString(16).substring(2,8))
// 输出: #f9eb3a

字节单位大小转换

export function byteSizeTransfer( kb ){
  let units = ['KB', 'MB', 'GB', 'TB', 'PB'];
  let unitIndex = 0;

  while (kb >= 1024 && unitIndex < units.length - 1) {
    kb /= 1024;
    unitIndex++;
    console.log("kb", kb, unitIndex)
  }

  return `${kb.toFixed(2)} ${units[unitIndex]}`;
}
let size = formatSizeUnits(124011230)
console.log("size", size)
// size 118.27 GB

前端分页函数

export const currentPageData = (currentPage, pageSize, arr) =>{
  let offset = (currentPage - 1) * pageSize;
  let pageData = (offset + pageSize >= arr.length)
    ? arr.slice(offset, arr.length)
    : arr.slice(offset, offset + pageSize);
  return pageData;
}

生成UUID

function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

export const getUUID = () => {
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

判断RGB颜色是深色还是浅色

export const colorDepth = ( R,G,B ) => {
    // if ( !R && !G && !B ) return ''
    let r = Number(R.replace(/[^0-9]/ig,"")) || 255
    let g = Number(G) || 255
    let b = Number(B) || 255
    const computedColorVal = r*0.299 + g*0.578 + b*0.114
    if( computedColorVal >= 192){
        return 'light' //浅色 ...
    }
    return 'dark'// 深色
}

判断一个对象是否为空

export const isEmpty = ( obj ) => {
    if ( typeof obj === 'number' && ( obj === 0 || obj === '0' ) ) return false
    return typeof obj === 'undefined' || !obj || JSON.stringify(obj) === '{}' || obj === 'null'
}

16进制颜色RGBA颜色

export const hex2Rgba = (hex = '#2c4dae', opacity) => {
    // if(!hex) hex = "#2c4dae";
    return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt("0x" + hex.slice(5, 7)) + "," + (opacity || "1") + ")";
}

数组对象去重

/**
 * 数组对象去重
 * param:1 数组对象
 * param:2 去重项标识
 * */
export const toRepetitionByObj = function ( arr, repetitionItem ) {
    if ( !isArray(arr) || !arr.length ) return []
    let obj = {}
    return arr.reduce((cur,next) => {
        obj[next[repetitionItem]] ? "" : obj[next[repetitionItem]] = true && cur.push(next);
        return cur;
    },[])
}

日期格式化

export function formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
  if (typeof date === 'string') {
    if (fmt.indexOf('hh:mm:ss') > -1) {
      let newDate = new Date();
      let minutes = newDate.getMinutes() < 9 ? `0${newDate.getMinutes()}` : `${newDate.getMinutes()}`
      return `${date} ${newDate.getHours()}:${ minutes }:${newDate.getSeconds()}`;
    }
    return date;
  }

  if (!date || date == null) return null;
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

判断两个时间区间是否重叠

/**
 * 判断两个时间区间是否重叠
 * @params timeA array[startTimeString,startTimeString]
 * @params timeB array[startTimeString,startTimeString]
 * @return boolean
 * */
const checkTimeOverlap = (timeA, timeB) => {
  if (!Array.isArray(timeA) || !Array.isArray(timeB)) return false
  const maxA = new Date(timeA[0]).getTime()
  const maxB = new Date(timeB[0]).getTime()
  const minA = new Date(timeA[1]).getTime()
  const minB = new Date(timeB[1]).getTime()
  const max = [maxA, maxB];
  const min = [minA, minB];
  console.log('timeA, timeB', timeA[0], timeB[0])
  console.log('max, min', max, min)
  return (Math.max.apply(null, max) <= Math.min.apply(null, min))
}

let a1 = ['2022-10-28 08:00:00', '2022-10-28 22:00:00']
let a2 = ['2022-10-28 10:19:00', '2022-10-28 23:19:00']

let result = checkTimeOverlap(a1, a2)

console.log('result', result)

生成自定义数据

export const getOptionsData = () => {
    return Array.from({length:100}, (v,k) => k).reduce( (prev, current) => {
      return prev = prev.concat({
        id: current,
        label: `${current}-data`,
        value: current
      })
    }, []);
  }

arraybuffer 转换 json

export function arrayBufferToJson( arrayBufferData ){
    // 使用TextDecoder
    let enc = new TextDecoder("utf-8");
    let uint8_msg = new Uint8Array(arrayBufferData);
    let jsonData = JSON.parse(enc.decode(uint8_msg));
    console.log(jsonData);
}

a 标签实现下载

export function downloadFile(blobFile, filename) {
    // 创建 blobUrl 该 Url会占用内存
    const blobUrl = URL.createObjectURL(blobFile)
    const aDom = document.createElement('a')
    aDom.href = blobUrl
    aDom.download = filename
    aDom.click()
    document.removeChild(aDom)
    // 释放 URL
    URL.revokeObjectURL(blobUrl)
}

clone

export const clone = ( obj ) => {
    if ( isArray(obj) || isObject(obj) ) {
        return JSON.parse(JSON.stringify(obj, function (key, value) {
            // console.log(key, value)
            if ( isFunction( value ) ) {
                // console.log('clone isFunction value',key, value)
                return Function.prototype.toString.call(value)
            }
            return value
        }))
    }
    return {}
}

高级分组

let arr1 =  [2,4,5,5,6,1,2]
let arr2 = [{ name: "ali", sex: "18" },{ name: "ali", sex: "18" },{ name: "boo", sex: "28" },{ name: "boo", sex: "28" }]
export function groupBy( arr, generatorKey ){
  let groupByResult = {};
  for (let item of arr) {
    // let key = item[prop];
    let key = generatorKey(item)
    if (!groupByResult[key]) {
      groupByResult[key] = [];
    }
    groupByResult[key].push(item)
  }
}

groupBy(arr1, (item) => item)

groupBy(arr2, (item) => item.name)

重写toFixed

/*
 * 处理精确问题
 * */
Number.prototype.toFixed = function (d) {
  return (Math.round(Number(this) * Math.pow(10, d)) / Math.pow(10, d)).toString();
}

EmitEvents订阅事件

class Bus {
  constructor() {
    // 记录回调函数名称
    this.callbacks = {}
  }

  $on(name, fun) {
    if(this.callbacks[name]){
      let args = this.callbacks[name]
      fun(args)
    }å
  }
  $emit(name, args) {
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(args)
  }
}

const bus = new Bus();

bus.$emit("foo", { name: "张三" })

bus.$on("foo", function( arg ){
    console.log("foo arg", arg)
})


bus.$emit("foo2", { name: "李四" })

bus.$on("foo2", function( arg ){
    console.log("foo2 arg", arg)
})