util.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const http = require('./http.js');
  2. const formatTime = date => {
  3. const year = date.getFullYear()
  4. const month = date.getMonth() + 1
  5. const day = date.getDate()
  6. const hour = date.getHours()
  7. const minute = date.getMinutes()
  8. const second = date.getSeconds()
  9. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  10. }
  11. const formatNumber = n => {
  12. n = n.toString()
  13. return n[1] ? n : '0' + n
  14. }
  15. // 保存用户信息数据
  16. const selfUserInfo = (global, force = false, name = 'selfUserInfo') => {
  17. return new Promise(resolve => {
  18. if (global[name] && !force) {
  19. resolve(global[name]);
  20. } else {
  21. http.get('/appletUser/getAccountInfo').then(({ status, data = {} }) => {
  22. if (status === 0) {
  23. global[name] = data;
  24. resolve(global[name]);
  25. } else {
  26. resolve(false)
  27. }
  28. }).catch(() => {
  29. resolve(false)
  30. })
  31. }
  32. })
  33. }
  34. // 生成随机数uuid
  35. const uuid = () => {
  36. var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  37. for (var r, chars = CHARS, uuid = new Array(30), rnd = 0, i = 0; 30 > i; i++) {
  38. 14 == i ? uuid[i] = "4" :
  39. (2 >= rnd && (rnd = 33554432 + 16777216 * Math.random() | 0), r = 15 & rnd, rnd >>= 4, uuid[i] = chars[19 == i ? 3 & r | 8 : r]);
  40. }
  41. return uuid.join("")
  42. }
  43. /* 数字格式化 */
  44. const numberFormat = (val, fixed = 2) => {
  45. if(typeof val != 'number' && !val) return '-';
  46. val = Number(val);
  47. if(typeof val != 'number') return val;
  48. if(typeof fixed == 'number' && fixed > 0) {
  49. val = val.toFixed(fixed);
  50. }
  51. const numArr = val.toString().split('.'),
  52. intNum = numArr[0],
  53. intNumFormat = intNum.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断
  54. let floatNum = '';
  55. if(numArr[1]) {
  56. floatNum = `.${numArr[1]}`
  57. }
  58. return `${intNumFormat}${floatNum}`
  59. }
  60. // 函数节流(throttle):函数在一段时间内多次触发只会执行第一次
  61. const throttle = (fn, gapTime) => {
  62. if (gapTime == null || gapTime == undefined) {
  63. gapTime = 1500
  64. }
  65. let _lastTime = null
  66. return function () {
  67. let _nowTime = + new Date()
  68. if (_nowTime - _lastTime > gapTime || !_lastTime) {
  69. // 将this和参数传给原函数
  70. fn.apply(this, arguments)
  71. _lastTime = _nowTime
  72. }
  73. }
  74. }
  75. module.exports = {
  76. formatTime: formatTime,
  77. selfUserInfo,
  78. uuid,
  79. numberFormat,
  80. customerId: 47, //47
  81. throttle: throttle
  82. }