工具函数

1. 节流函数

  1. /**
  2. * 节流函数
  3. * fn是我们需要包装的事件回调, interval是时间间隔的阈值
  4. */
  5. const throttle = (fn, interval) => {
  6. // last为上一次触发回调的时间
  7. let last = 0
  8. interval = interval || 1000
  9. // 将throttle处理结果当作函数返回
  10. return function () {
  11. // 保留调用时的this上下文
  12. let context = this
  13. // 保留调用时传入的参数
  14. let args = arguments
  15. // 记录本次触发回调的时间
  16. let now = +new Date()
  17. // 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值
  18. if (now - last >= interval) {
  19. // 如果时间间隔大于我们设定的时间间隔阈值,则执行回调
  20. last = now
  21. fn.apply(context, args)
  22. }
  23. }
  24. }

2. 深拷贝

  1. function cloneDeep(data) {
  2. let copyed_objs = [] // 此数组解决了循环引用和相同引用的问题,它存放已经递归到的目标对象
  3. function _deepCopy(target) {
  4. if (typeof target !== 'object' || !target) {
  5. return target
  6. }
  7. for (let i = 0; i < copyed_objs.length; i++) {
  8. if (copyed_objs[i].target === target) {
  9. return copyed_objs[i].copyTarget
  10. }
  11. }
  12. let obj = {}
  13. if (Array.isArray(target)) {
  14. obj = [] // 处理target是数组的情况
  15. }
  16. copyed_objs.push({ target: target, copyTarget: obj })
  17. Object.keys(target).forEach(key => {
  18. if (obj[key]) {
  19. return
  20. }
  21. obj[key] = _deepCopy(target[key])
  22. })
  23. return obj
  24. }
  25. return _deepCopy(data)
  26. }

3. 生成UUID

  1. /**
  2. * 生成UUID
  3. */
  4. function generateUUID() {
  5. let d = new Date().getTime()
  6. let uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7. // let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  8. let r = (d + Math.random() * 16) % 16 | 0
  9. d = Math.floor(d / 16)
  10. return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
  11. })
  12. return uuid
  13. }

URL

1. 获取 url 中指定参数

  1. function getQueryString(url, name) {
  2. var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  3. var r = url.substr(1).match(reg)
  4. if (r != null) {
  5. return r[2]
  6. }
  7. return null
  8. }

2. 更新 url 中某个 key 的 value 值

  1. /**
  2. * 更新url中某个key的value值
  3. * @param {} uri
  4. * @param {*} key
  5. * @param {*} value
  6. */
  7. function updateQueryStringParameter(uri, key, value) {
  8. var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i')
  9. var separator = uri.indexOf('?') !== -1 ? '&' : '?'
  10. if (uri.match(re)) {
  11. return uri.replace(re, '$1' + key + '=' + value + '$2')
  12. } else {
  13. return uri + separator + key + '=' + value
  14. }
  15. }

3. 拼接对象为请求字符串

  1. /**
  2. * 拼接对象为请求字符串
  3. * @param {Object} obj - 待拼接的对象
  4. * @returns {string} - 拼接成的请求字符串
  5. */
  6. const encodeUrlParams = obj => {
  7. const params = []
  8. Object.keys(obj).forEach(key => {
  9. let value = obj[key]
  10. // 如果值为undefined我们将其置空
  11. if (typeof value === 'undefined') {
  12. value = ''
  13. }
  14. // 对于需要编码的文本(比如说中文)我们要进行编码
  15. params.push([key, value].join('='))
  16. // params.push([key, encodeURIComponent(value)].join('='))
  17. })
  18. return params.join('&')
  19. }

4. 返回一个13位的时间戳

  1. const timestamp = () => new Date().getTime()

数组

1. 数组打乱顺序

  1. function shuffle(arr) {
  2. let length = arr.length,
  3. randomIndex,
  4. temp
  5. while (length) {
  6. randomIndex = Math.floor(Math.random() * length--)
  7. temp = arr[randomIndex]
  8. arr[randomIndex] = arr[length]
  9. arr[length] = temp
  10. }
  11. return arr
  12. }

2. 数组分组

  1. function groupBy(array, fn) {
  2. const groups = {}
  3. array.forEach(function (item) {
  4. const group = JSON.stringify(fn(item))
  5. // 这里利用对象的key值唯一性的,创建数组
  6. groups[group] = groups[group] || []
  7. groups[group].push(item)
  8. })
  9. // 最后再利用map循环处理分组出来
  10. return Object.keys(groups).map(function (group) {
  11. return groups[group]
  12. })
  13. }
  14. // e.g
  15. // const tempList = _operate.groupBy(prizeList, e => {
  16. // return [e.startTime]
  17. // })

3. 根据对象中的某个属性值来进行排序

  1. /**
  2. * 根据对象中的某个属性值来进行排序
  3. * @param {*} property 属性值
  4. * @param {*} type 排序方式 down:降序;默认升序
  5. * arr.sort(compareSort('price'));
  6. */
  7. function compareSort(property, type) {
  8. return function (a, b) {
  9. let value1 = a[property]
  10. let value2 = b[property]
  11. let result = type === 'down' ? value2 - value1 : value1 - value2
  12. return result
  13. }
  14. }

4. 降维

  1. /**
  2. * 降维
  3. * @param {*} arr
  4. * @returns
  5. */
  6. function flat(list) {
  7. return list.reduce((acc, val) => acc.concat(val), [])
  8. }

5. 数组运算

  1. /**
  2. * 数组运算
  3. * @param {*} a 数组1
  4. * @param {*} b 数组2
  5. * @param {*} type 运算属性(交集——intersect,差集——minus,补集——complement,并集——unionSet)
  6. * @returns
  7. */
  8. function calculationArray(a, b, type) {
  9. type = type ? type : 'intersect' //默认交集运算
  10. let sa = new Set(a)
  11. let sb = new Set(b)
  12. let result = []
  13. switch (type) {
  14. case 'intersect':
  15. // 交集
  16. result = a.filter(x => sb.has(x))
  17. break
  18. case 'minus':
  19. // 差集
  20. result = a.filter(x => !sb.has(x))
  21. break
  22. case 'complement':
  23. // 补集
  24. result = [...a.filter(x => !sb.has(x)), ...b.filter(x => !sa.has(x))]
  25. break
  26. case 'unionSet':
  27. // 并集
  28. result = Array.from(new Set([...a, ...b]))
  29. break
  30. default:
  31. result = a.filter(x => sb.has(x))
  32. break
  33. }
  34. return result
  35. }

数据转换

1. 金额

  1. /**
  2. * 千分位 && 小数点后两位
  3. */
  4. function handlePrice(num) {
  5. num = num || 0
  6. num = parseFloat(num.toFixed(2)).toString()
  7. let d = ''
  8. if (num.slice(0, 1) === '-') {
  9. d = num.slice(0, 1)
  10. num = num.slice(1)
  11. }
  12. const len = num.length
  13. const index = num.indexOf('.')
  14. if (index === -1) {
  15. num = num + '.00'
  16. } else if (index + 2 === len) {
  17. num = num + '0'
  18. }
  19. const index2 = num.indexOf('.') // 字符出现的位置
  20. const num2 = num.slice(-3)
  21. num = num.slice(0, index2)
  22. let result = ''
  23. while (num.length > 3) {
  24. result = ',' + num.slice(-3) + result
  25. num = num.slice(0, num.length - 3)
  26. }
  27. if (num) {
  28. result = num + result
  29. }
  30. return d + (result + num2)
  31. }

2. 字节对象转字符串

  1. /**
  2. * 字节对象转字符串
  3. * @param {Object} arr
  4. */
  5. export const byteToString = function (arr) {
  6. if (typeof arr === 'string') {
  7. return arr
  8. }
  9. var str = '',
  10. _arr = arr
  11. for (var i = 0; i < _arr.length; i++) {
  12. var one = _arr[i].toString(2),
  13. v = one.match(/^1+?(?=0)/)
  14. if (v && one.length == 8) {
  15. var bytesLength = v[0].length
  16. var store = _arr[i].toString(2).slice(7 - bytesLength)
  17. for (var st = 1; st < bytesLength; st++) {
  18. store += _arr[st + i].toString(2).slice(2)
  19. }
  20. str += String.fromCharCode(parseInt(store, 2))
  21. i += bytesLength - 1
  22. } else {
  23. str += String.fromCharCode(_arr[i])
  24. }
  25. }
  26. return str
  27. }

3. 字符串转字节

  1. /**
  2. * 字符串转字节
  3. * @param {Object} str
  4. */
  5. export const stringToArrayBuffer = function (str) {
  6. // 首先将字符串转为16进制
  7. let val = ''
  8. for (let i = 0; i < str.length; i++) {
  9. if (val === '') {
  10. val = str.charCodeAt(i).toString(16)
  11. } else {
  12. val += ',' + str.charCodeAt(i).toString(16)
  13. }
  14. }
  15. // 将16进制转化为ArrayBuffer
  16. return new Uint8Array(
  17. val.match(/[\da-f]{2}/gi).map(function (h) {
  18. return parseInt(h, 16)
  19. })
  20. ).buffer
  21. }

4. 移除空字符 (\u0000)

  1. export const removeNullCharacter = str => {
  2. return str.replace(/\\u([0-9]|[a-fA-F])([0-9]|[a-fA-F])([0-9]|[a-fA-F])([0-9]|[a-fA-F])/g, '')
  3. }

5. 格式化空字符为空字符串

  1. /**
  2. * e.g: \u0000 => ''
  3. */
  4. export const formatNullCharacter = str => {
  5. if (!str) return ''
  6. return JSON.parse(removeNullCharacter(JSON.stringify(str)))
  7. }