前端开发常用函数

1、js读取视频长度

/**
 * 读取视频长度(秒数)
 */
export function ReadVideoLength(file){
  return new Promise((resolve,reject)=>{
    let url = URL.createObjectURL(file);
    let audioElement = new Audio(url);
    audioElement.addEventListener("loadedmetadata", (_event)=> {
      let duration = parseInt(audioElement.duration);
      resolve(duration)
    });
  })
}

2、判断对象是否有某个属性

/**
 * 判断是否有某个属性
 */
export function hasOwn(val, key){
  const hasOwnProperty = Object.prototype.hasOwnProperty;
  return hasOwnProperty.call(val, key);
}

3、节流

export function throttle(callBack, time) {
  let timer = null;
  //timer状态要常驻内存,这里做了一个闭包
  return function () {
    if (!timer) {
      timer = setTimeout(() => {
        callBack()
        timer = null
      }, time)
    }
  }
}

4、获取当前格式化日期时间

export function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

5、判断是否为对象类型

export function isObject(val){
  return val !== null && typeof val === 'object';
}

6、判断图片是否超出高度/宽度

/**
 * 判断是否超出宽度限制
 * @param {*} file
 * @returns
 */
export function isSize(file) {
  return new Promise(function (resolve, reject) {
    const width = 1080
    const _URL = window.URL || window.webkitURL
    const img = new Image()
    img.onload = function () {
      const valid = img.width <= width
      valid ? resolve() : reject()
    }
    img.src = _URL.createObjectURL(file)
  }).then(
    () => {
      return file
    },
    () => {
      return Promise.reject()
    }
  )
}

7、改变文件格式

import { filetoDataURL, dataURLtoImage, imagetoCanvas, canvastoDataURL, dataURLtoFile } from 'image-conversion'
/**
 * 改变文件格式
 * @param {} file
 * @param {*} config
 * @returns
 */
async function ChanageStyle(file, config = {}) {
  if (!(file instanceof Blob)) {
    throw new Error('compress(): First arg must be a Blob object or a File object.');
  }
  if (typeof config !== 'object') {
    config = Object.assign({
      quality: config,
    });
  }
  config.quality = Number(config.quality);
  if (Number.isNaN(config.quality)) {
    return file;
  }
  const dataURL = await filetoDataURL(file);
  let originalMime = 'image/jpeg';
  let mime = 'image/jpeg'; // 默认压缩类型
  const image = await dataURLtoImage(dataURL);
  const canvas = await imagetoCanvas(image, Object.assign({}, config));
  const compressDataURL = await canvastoDataURL(canvas, config.quality, mime);
  const compressFile = await dataURLtoFile(compressDataURL, originalMime);
  return compressFile;
};

8、深度合并对象

function isMergeableObject(val) {
  var nonNullObject = val && typeof val === 'object'

  return nonNullObject &&
    Object.prototype.toString.call(val) !== '[object RegExp]' &&
    Object.prototype.toString.call(val) !== '[object Date]'
}

function emptyTarget(val) {
  return Array.isArray(val) ? [] : {}
}

function cloneIfNecessary(value, optionsArgument) {
  var clone = optionsArgument && optionsArgument.clone === true
  return (clone && isMergeableObject(value)) ? deepmerge(emptyTarget(value), value, optionsArgument) : value
}

function defaultArrayMerge(target, source, optionsArgument) {
  var destination = target.slice()
  source.forEach(function (e, i) {
    if (typeof destination[i] === 'undefined') {
      destination[i] = cloneIfNecessary(e, optionsArgument)
    } else if (isMergeableObject(e)) {
      destination[i] = deepmerge(target[i], e, optionsArgument)
    } else if (target.indexOf(e) === -1) {
      destination.push(cloneIfNecessary(e, optionsArgument))
    }
  })
  return destination
}

function mergeObject(target, source, optionsArgument) {
  var destination = {}
  if (isMergeableObject(target)) {
    Object.keys(target).forEach(function (key) {
      destination[key] = cloneIfNecessary(target[key], optionsArgument)
    })
  }
  Object.keys(source).forEach(function (key) {
    if (!isMergeableObject(source[key]) || !target[key]) {
      destination[key] = cloneIfNecessary(source[key], optionsArgument)
    } else {
      destination[key] = deepmerge(target[key], source[key], optionsArgument)
    }
  })
  return destination
}

/**
 * 深度合并对象
 * @param {*} target
 * @param {*} source
 * @param {*} optionsArgument
 * @returns
 */
export function deepmerge(target, source, optionsArgument) {
  var array = Array.isArray(source)
  var options = optionsArgument || { arrayMerge: defaultArrayMerge }
  var arrayMerge = options.arrayMerge || defaultArrayMerge

  if (array) {
    return Array.isArray(target) ? arrayMerge(target, source, optionsArgument) : cloneIfNecessary(source, optionsArgument)
  } else {
    return mergeObject(target, source, optionsArgument)
  }
}

9、压缩图片导出

/*
    npm install image-conversion
*/
import { filetoDataURL, dataURLtoImage, imagetoCanvas, canvastoDataURL, dataURLtoFile } from 'image-conversion'
/**
 * @function ICON导出
 * @param { width ,fileName, quality,file }
 */

export function pressImg(param) {
  if (param) {
    param.width = param.hasOwnProperty('width') ? param.width : -1
    param.fileName = param.hasOwnProperty('fileName') ? param.fileName : 'image'
    param.quality = param.hasOwnProperty('quality') ? param.quality : 0.92
    var fileType = 'image/png'
    var image = new Image()
    image.src = param.file
    image.setAttribute('crossOrigin', 'Anonymous')
    image.onload = function () {
      var scale = image.width / image.height
      var canvas = document.createElement('canvas')
      var context = canvas.getContext('2d')
      canvas.width = param.width == -1 ? image.width : param.width
      canvas.height = param.width == -1 ? image.height : parseInt(param.width / scale)
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
      var newImageData = canvas.toDataURL(fileType, param.quality)
      // 创建下载
      var link = document.createElement('a')
      link.download = param.fileName
      link.href = newImageData
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
}

10、封装白山云上传函数

/**
 *
 * @param {} 白山云oss上传
 * @returns
 */
export function AwsUpload(bucket_name) {
  const AWS = require('aws-sdk')
  AWS.config.update({ accessKeyId: 'your accessKeyId', secretAccessKey: 'your secretAccessKey' })
  AWS.config.region = 'us-west-1'
  AWS.config.endpoint = 'http://ss.bscstorage.com'
  AWS.config.s3ForcePathStyle = true
  var s3 = new AWS.S3({ params: { Bucket: bucket_name, ACL: 'public-read' } })
  return s3
}

11、生成随机唯一字符串

import { nanoid } from 'nanoid'
/**
 * 生成唯一字符串
 * @param {number} num
 */
export function generateStr(num) {
  return nanoid(num)
}

12、获取get请求query参数

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

13、获取字节长度

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

14、清空数组

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

15、参数转对象

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

16、html 转txt

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

17

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

18

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

19、防抖

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result
  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }
    return result
  }
}

20、

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值