const http = require('./http.js'); const formatTime = date => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } // 保存用户信息数据 const selfUserInfo = (global, force = false, name = 'selfUserInfo') => { return new Promise(resolve => { if (global[name] && !force) { resolve(global[name]); } else { http.get('/appletUser/getAccountInfo').then(({ status, data = {} }) => { if (status === 0) { global[name] = data; resolve(global[name]); } else { resolve(false) } }).catch(() => { resolve(false) }) } }) } // 生成随机数uuid const uuid = () => { var CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""); for (var r, chars = CHARS, uuid = new Array(30), rnd = 0, i = 0; 30 > i; i++) { 14 == i ? uuid[i] = "4" : (2 >= rnd && (rnd = 33554432 + 16777216 * Math.random() | 0), r = 15 & rnd, rnd >>= 4, uuid[i] = chars[19 == i ? 3 & r | 8 : r]); } return uuid.join("") } /* 数字格式化 */ const numberFormat = (val, fixed = 2) => { if(typeof val != 'number' && !val) return '-'; val = Number(val); if(typeof val != 'number') return val; if(typeof fixed == 'number' && fixed > 0) { val = val.toFixed(fixed); } const numArr = val.toString().split('.'), intNum = numArr[0], intNumFormat = intNum.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断 let floatNum = ''; if(numArr[1]) { floatNum = `.${numArr[1]}` } return `${intNumFormat}${floatNum}` } // 函数节流(throttle):函数在一段时间内多次触发只会执行第一次 const throttle = (fn, gapTime) => { if (gapTime == null || gapTime == undefined) { gapTime = 1500 } let _lastTime = null return function () { let _nowTime = + new Date() if (_nowTime - _lastTime > gapTime || !_lastTime) { // 将this和参数传给原函数 fn.apply(this, arguments) _lastTime = _nowTime } } } module.exports = { formatTime: formatTime, selfUserInfo, uuid, numberFormat, customerId: 47, //47 throttle: throttle }