项目中常用的utils

import crypto from 'crypto'
import SparkMD5 from 'spark-md5'
import CryptoJs from 'crypto-js'
import JSEncrypt from 'jsencrypt'
import storage from '@/utils/storage'
import { isEmpty, isArray, remove } from 'lodash-es'
import { chartColor, regexIP, unitOptions } from '@/utils/info'
/**
 * ascSortData 升序
 * @param {Array}  arr  数据
 * return Array
 */
export const ascSortData = arr => arr.sort((a, b) => a.value - b.value)

/**
 * descSortData 降序
 * @param {Array}  arr  数据
 * return Array
 */
export const descSortData = arr => isArray(arr) ? arr.sort((a, b) => b.value - a.value) : arr

/**
 * formatterAddIpData 格式化新建IP数据
 * @param {Array}  arr  数据 [{start: 1, end: 2}]
 * return ['start-end']
 */
export function formatterAddIpData(arr) {
  return arr.reduce((item, prev, index) => {
    item[index] = `${prev.start || ''}-${prev.end || ''}`
    return item
  }, [])
}

/**
 * firstUpperCase 首字母大写
 * @param  {String}  str  字符串
 * return String
 */
export const firstUpperCase = str => str.toLowerCase().replace(/^\S/g, s => s.toUpperCase())

/**
 * lowercaseCase 字符串小写
 * @param  {String}  str  字符串
 * return String
 */
export const lowercaseCase = str => str.toLocaleLowerCase()

/**
 * findArrayIndex 查找数组下标 - value index
 * @param  {Array}   arr    数据
 * @param  {String}  key    类型
 * @param  {String}  value  结果
 * return Number 下标
 */
export function findArrayIndex(arr, key, value) {
  return isArray(arr) ? arr.findIndex(item => item[key] === value) : -1
}

/**
 * pMessage  重置element - message 的top 为防止多次提交时显示问题
 * @param  {String}  message
 * @param  {String}  type   ['success', 'error', 'warning', 'info']
 * @param  {Number}  duration
 *
 */
let zIndexNum = 20000
export function pMessage(options, callback) {
  const { message, duration, type } = options
  const zIndex = zIndexNum++

  const obj = document.createElement('div')
  obj.id = `message${zIndex}`

  const className = type || 'success'

  obj.innerHTML = ``

  document.body.appendChild(obj)
  setTimeout(() => {
    document.body.removeChild(obj)
    callback && callback()
  }, duration || 2000)
}

/**
 * 255.255.255.255有益出
 */
export function ipToInt(ip) {
  if (!ip) {
    throw new Error('E_UNDEFINED_IP')
  }

  if (!regexIP.test(ip)) {
    throw new Error('E_INVALID_IP')
  }
  return ip
    .split('.')
    .map((octet, index, array) => {
      return parseInt(octet) * Math.pow(256, array.length - index - 1)
    })
    .reduce((prev, curr) => {
      return prev + curr
    })
}

export function intToIp(value) {
  if (!value) {
    throw new Error('E_UNDEFINED_INTEGER')
  }

  const result = /\d+/.exec(value)

  if (!result) {
    throw new Error('E_INTEGER_NOT_FOUND')
  }

  value = result[0]

  return [(value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff].join('.')
}

/**
 * intersect 取数组交集
 * @param  {Array}  original   原始数组
 * @param  {Array}  arr        对比数组
 * return Array-[]
 */
export function intersect(original, arr) {
  if (!isArray(original) || !isArray(original)) {
    return original
  }
  const packageData = new Set(arr)
  return original.filter(el => packageData.has(el))
}

/**
 * minus 取数组差集
 * @param  {Array}  original   原始数组
 * @param  {Array}  arr        对比数组
 * return Array-[]
 */
export function minus(original, arr) {
  if (!isArray(original) || !isArray(original)) {
    return original
  }
  const packageData = new Set(arr)
  return original.filter(el => !packageData.has(el))
}

/**
 * complement 取数组补集
 * @param  {Array}  original   原始数组
 * @param  {Array}  arr        对比数组
 * return Array-[]
 */
export function complement(original, arr) {
  if (!isArray(original) || !isArray(original)) {
    return original
  }
  const packageOriginal = minus(original, arr)
  const packageData = minus(arr, original)
  return [...packageOriginal, ...packageData]
}

/**
 * unionSet 取数组并集
 * @param  {Array}  original   原始数组
 * @param  {Array}  arr        对比数组
 * return Array-[]
 */
export function unionSet(original, arr) {
  if (!isArray(original) || !isArray(original)) {
    return original
  }
  return Array.from(new Set([...original, ...arr]))
}

/**
 * dataEmptyFilter 格式化数据
 * @param   {String}  str  str
 * @returns {String}
 */
export function dataEmptyFilter(str) {
  if (!str && str !== 0) {
    return '-'
  }
  return str
}

/**
 * 密码 MD5加密
 * @param {String} pwd 密码
 */
export function getMd5(pwd) {
  const md5 = crypto.createHash('md5')
  md5.update(pwd)
  const password = md5.digest('hex')
  return password
}

/**
 * getFileMD5 获取文件的md5
 * @param   {Object}   file        加密文件
 * @param   {Object}   onProgress  进度回调
 * return Promise
 */
export function getFileMD5(file, onProgress) {
  if (!file) return false
  // 最大值
  const chunkSize = 1024 * 1024 * 2
  const { size } = file
  const chunks = Math.ceil(size / chunkSize)
  // 文件开始值
  let currentChunk = 0
  // 创建 md5 加密对象  32位
  const spark = new SparkMD5.ArrayBuffer()
  // 创建读取文件对象
  const fileReader = new FileReader()

  function loadNext() {
    const start = currentChunk * chunkSize
    const end = start + chunkSize >= size ? size : start + chunkSize
    fileReader.readAsArrayBuffer(file.slice(start, end))
  }

  return new Promise((resolve, reject) => {
    fileReader.onload = e => {
      // 设置md5内容
      const sparkObj = spark.append(e.target.result)
      // 自动追加
      currentChunk += 1
      // 当前开始值追加后小于最大截取值时
      if (currentChunk < chunks) {
        if (onProgress) {
          const percent = parseInt((currentChunk * chunkSize * 100) / size)
          onProgress(percent)
        }
        loadNext()
      } else {
        onProgress && onProgress(100)
        return resolve({
          md5: sparkObj.end()
        })
      }
    }
    // 切分文件
    loadNext()
    // 读取报错
    fileReader.onerror = () => {
      return reject({
        md5: 0
      })
    }
  })
}

/**
 * getFileSha1 获取文件sha1
 * @param   {Object}   file        加密文件
 * @returns
 */
export async function getFileSha1(file) {
  const reader = new FileReader()
  if (!file) {
    return ''
  }

  return new Promise((resolve, reject) => {
    reader.onload = function() {
      const fileResult = this.result
      const fileWordArr = CryptoJs.lib.WordArray.create(fileResult)
      const sha1Hash = CryptoJs.SHA1(fileWordArr)
      return resolve({
        sha1: sha1Hash.toString()
      })
    }

    reader.readAsArrayBuffer(file)
  })
}

/**
 * arrayConversion  数组转化
 * @param {Array}  value   源数据
 * @param {Array}  srcValue   目的数据
 * @returns
 */
export const arrayConversion = (value, result) => {
  if (isArray(value)) {
    value = []
    return result
  }
}

/**
 * arrayConversionToObject  数组转对象
 * @param  {Array}  options 源数据
 * @returns []
 */
export const arrayConversionToObject = options =>
  options.map(el => el.key).reduce((acc, cur) => ({ ...acc, [cur]: 0 }), {})

/**
 * objectConversionToInitData  对象转数组
 * @param  {Array}  options 源数据
 * @returns []
 */
export const objectConversionToInitData = options =>
  Object.keys(options).reduce((acc, cur) => ({ ...acc, [cur]: 0 }), {})

/**
 * serializationDataStyle  序列化化数据style
 * @param {Array}   arr
 * @param {Number}  color  色值
 */
export let colorData = []
export const serializationDataStyle = (arr, color = 120, parent = false) => {
  return arr.map((item, index) => {
    chartColor[item.name] && (colorData = chartColor[item.name])
    const color = parent ? colorData[0] : colorData[index + 1]
    item.itemStyle = {
      color
    }
    item.textStyle = {
      color
    }
    if (item.children && item.children.length) {
      serializationDataStyle(item.children, color, false)
    }
    return item
  })
}

/**
 * arrayToHeavy  数组去重
 * @param {Array} data
*/
export const arrayToHeavy = (data) => Array.from(new Set(data))

/**
 * flattenArray  拉平多组数组
 * @param {Array} data
 */
export const flattenArray = (data) => data.reduce((flat, toFlat) => flat.concat(Array.isArray(toFlat) ? flattenArray(toFlat) : toFlat), [])

/**
 * updateArrayData 更新数组 解决vue2.0数组更新问题
 * @param {Array} data
 * @param {Array} result
 */
export const updateArrayData = (data, result) => {
  remove(result)
  data.map((el, index) => result.splice(index, 1, el))
  return result
}

/**
 * fillZero 个位补零
 * @param  {Number}  num  数字
 */
export const fillZero = (num) => `${num}`.padStart(2, '0')

/**
 * sum 数组算和
 * @param {Array} arr  数组
 * return num
 */
export const sum = (arr) => (arr.reduce((acc, cur) => (acc += cur.value), 0))

/**
 * createSizeArr
 * @param {Number}  size  长度
 * @param {Number}  step  步长
*/
export const createSizeArr = (size, step = 1) => Array.from(new Array(size), (value, index) => (index * step))

/**
 * getLocalStorage
 * @param {String} type
 * @param {String} name
 * @param {Number} result
 * @returns
 */
export function getLocalStorage(type = 'unrepaired', name = 'hostLeakFix', result = 0) {
  try {
    return storage.get(name)[type] || result
  } catch (error) {
    return result
  }
}

/*
  千位分隔
*/
export const numberWithCommas = (x) => x.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,')

/**
 * diffObject 获取对象值
 * @param  {Number}  target  开始时间戳
 * @param  {Number}  source    结束时间戳
*/
export function diffObject(target, source) {
  for (const key in target) {
    target[key] = source[key] || ''
  }
  return target
}

/**
 * formatNetworkSpeed 字节转化
 * @param {Number} speed      网速值,值单位 KB
 * @param {Number} decimals   小数位数
 */
export function formatNetworkSpeed(speed, decimals = 2) {
  if (!speed) return '0 Bytes'
  const num = 1024.00 // byte

  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const single = Math.floor(Math.log(speed) / Math.log(num))
  return `${parseFloat((speed / Math.pow(num, single)).toFixed(decimals))} ${sizes[single]}`
}

/**
 * getPercentWithPrecision 通过点数获取数据
 * @param  {Number}   value        值
 * @param  {Number}   total        总数
 * @param  {Number}   precision    点位
 */
export const getPercentWithPrecision = (value, total, precision = 1) => {
  if (!value || !total) {
    return 0
  }

  const digits = Math.pow(10, precision)
  const result = (isNaN(value) ? 0 : value) / total * digits * 100
  return Math.floor(result) / digits
}
/**
 * 千万单位截取 millionUnitFormat
 * @param {Number}   number  值
 * @returns
 */
export function millionUnitFormat(number, type = 'number') {
  if (!`${number}`) {
    return 0
  }
  const len = `${number}`.length
  const digits = len > 4 ? 4 : 3
  const reg = new RegExp(`(\\d)(?=(?:\\d{${digits}})+$)`)
  const regPoint = new RegExp(`(\\d)(?=(?:\\d{${digits}})+$)`, 'g')
  const result = `${number}`.replace(reg, digits === 4 ? '$1.' : '$1,')
  const point = `${number}`.replace(regPoint, digits === 4 ? '$1.' : '$1,')
  const pointLen = point.split('.').length - 1

  if (type === 'json') {
    return {
      name: unitOptions[pointLen],
      value: digits === 4 ? Number(result).toFixed(2) / 1 : result,
      total: `${digits === 4 ? Number(result).toFixed(2) / 1 : result}${unitOptions[pointLen]}`
    }
  }

  return `${digits === 4 ? Number(result).toFixed(2) / 1 : result}${unitOptions[pointLen]}`
}

/**
 * isObject 判断是否为对象
 * @param {Object} arg
 * @returns
 */
export const isObject = function(arg) {
  return Object.prototype.toString.call(arg) === '[object Object]'
}

/**
 * isEmptyObject 判断是否为空对象
 * @param   {objcet}  data
 * @returns
 */
export const isEmptyObject = (data) => {
  return !isEmpty(data) && !Object.keys(data).length
}
/**
 * numFormat 千分位分隔符
 * @param   {objcet}  data
 * @returns
 */
export const numFormat = (num) => {
  var res = num.toString().replace(/\d+/, function(n) {
    return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) {
      return $1 + ','
    })
  })
  return res
}

/**
 * rsaByPublicKey  rsa 加密
 * @param {String}   pubKey   公钥
 * @param {String}   value    值
 * @param {String}   type     encrypt | decrypt
 * @returns string value
 */
export const rsaByPublicKey = (pubKey, value, type = 'encrypt') => {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey(pubKey)
  return encrypt[type](value)
}

你可能感兴趣的:(javascript,前端,开发语言)