util.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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('/user/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. /*
  76. 开鲁
  77. appid: "wx574e071aee652e48"
  78. customerId: 60
  79. */
  80. module.exports = {
  81. formatTime: formatTime,
  82. selfUserInfo,
  83. uuid,
  84. numberFormat,
  85. customerId: 47, //60
  86. throttle: throttle
  87. }