export function readTextFile(file, callback) {var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {if (rawFile.readyState === 4 && rawFile.status == "200") {var res = JSON.parse(rawFile.responseText)
callback(res);
}
}
rawFile.send(null);
}
export function isRealNum(val) {// isNaN() 函数 把空串 空格 以及 NUll 依照 0 来解决 所以先去除,if (val === "" || val == null) {return false;}
if (!isNaN(val)) {// 对于空数组和只有一个数值成员的数组或全是数字组成的字符串,isNaN 返回 false,例如:'123'、[]、[2]、['123'],isNaN 返回 false,
// 所以如果不须要 val 蕴含这些非凡状况,则这个判断改写为 if(!isNaN(val) && typeof val === 'number' )
return true;
} else {return false;}
}
export function isEmpty(v) {switch (typeof v) {
case 'undefined':
return true;
case 'string':
if (v.replace(/(^[ \t\n\r]*)|([\t\n\r]*$)/g, '').length == 0) return true;
break;
case 'boolean':
if (!v) return true;
break;
case 'number':
if (0 === v || isNaN(v)) return true;
break;
case 'object':
if (null === v || v.length === 0) return true;
for (var i in v) {return false;}
return true;
}
return false;
}
- 数组依据数组对象中的某个属性值进行排序的办法
- 应用例子:newArray.sort(sortBy(‘number’,false)) // 示意依据 number 属性降序排列; 若第二个参数不传递,默认示意升序排序
- @param attr 排序的属性 如 number 属性
- @param rev true 示意升序排列,false 降序排序
export function sortBy(attr, rev) {
// 第二个参数没有传递 默认升序排列
if (rev == undefined) {rev = 1;} else {rev = (rev) ? 1 : -1;
}
return function(a, b) {a = a[attr];
b = b[attr];
if (a < b) {return rev * -1;}
if (a > b) {return rev * 1;}
return 0;
}
}
export function isPoneAvailable(str) {var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
if (!myreg.test(str)) {return false;} else {return true;}
}
- @param Function fn 延时调用函数
- @param Number delay 提早多长时间
- @param Number atleast 至多多长时间触发一次
- @return Function 提早执行的办法
export function throttle(fn, delay = 500, atleast = 1000) {
var timer = null;
var previous = null;
return function() {var now = +new Date();
if (!previous) previous = now;
if (atleast && now - previous > atleast) {fn();
// 重置上一次开始工夫为本次完结工夫
previous = now;
clearTimeout(timer);
} else {clearTimeout(timer);
timer = setTimeout(function() {fn();
previous = null;
}, delay);
}
}
}
export function stringToByte(base64) {var arr = base64.split(',')
var str = atob(arr[1])
var bytes = []
var len, c
len = str.length
for (var i = 0; i < len; i++) {c = str.charCodeAt(i)
if (c >= 0x010000 && c <= 0x10FFFF) {bytes.push(((c >> 18) & 0x07) | 0xF0)
bytes.push(((c >> 12) & 0x3F) | 0x80)
bytes.push(((c >> 6) & 0x3F) | 0x80)
bytes.push((c & 0x3F) | 0x80)
} else if (c >= 0x000800 && c <= 0x00FFFF) {bytes.push(((c >> 12) & 0x0F) | 0xE0)
bytes.push(((c >> 6) & 0x3F) | 0x80)
bytes.push((c & 0x3F) | 0x80)
} else if (c >= 0x000080 && c <= 0x0007FF) {bytes.push(((c >> 6) & 0x1F) | 0xC0)
bytes.push((c & 0x3F) | 0x80)
} else {bytes.push(c & 0xFF)
}
}
return bytes
}
export function fmtDateVisualization(time) {
//#ifdef APP-PLUS
//app 端应用以下办法有误, 暂不知 起因, 间接截取返回
return time.slice(0, 10);
//#endif
if (!time) {return '未知';}
var newDate = new Date(time);
var updateTime = newDate.getTime();
let now = new Date().getTime()
let second = Math.floor((now - updateTime) / (1000))
let minute = Math.floor(second / 60)
let hour = Math.floor(minute / 60)
let day = Math.floor(hour / 24)
let month = Math.floor(day / 31)
let year = Math.floor(month / 12)
if (month > 0) {let rq = newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate();
return rq;
} else if (day > 0) {
let ret = day + '天前'
if (day >= 7 && day < 14) {ret = '1 周前'} else if (day >= 14 && day < 21) {ret = '2 周前'} else if (day >= 21 && day < 28) {ret = '3 周前'} else if (day >= 28 && day < 31) {ret = '4 周前'}
return ret
} else if (hour > 0) {return hour + '小时前'} else if (minute > 0) {return minute + '分钟前'} else if (second > 0) {return second + '秒前'} else {return '刚刚'}
}
function isInteger(obj) {return Math.floor(obj) === obj
}
- 如 3.14 >> 314,倍数是 100
- @param floatNum {number} 小数
- @return {object}
- {times:100, num: 314}
function toInteger(floatNum) {
var ret = {
times: 1,
num: 0
};
if (isInteger(floatNum)) {
ret.num = floatNum;
return ret
}
var strfi = floatNum + '';
var dotPos = strfi.indexOf('.');
var len = strfi.substr(dotPos + 1).length;
var times = Math.pow(10, len);
var intNum = parseInt(floatNum * times + 0.5, 10);
ret.times = times;
ret.num = intNum;
return ret
}
- 思路:把小数放大为整数(乘),进行算术运算,再放大为小数(除)
- @param a {number} 运算数 1
- @param b {number} 运算数 2
- @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
function operation(a, b, op) {var o1 = toInteger(a);
var o2 = toInteger(b);
var n1 = o1.num;
var n2 = o2.num;
var t1 = o1.times;
var t2 = o2.times;
var max = t1 > t2 ? t1 : t2;
var result = null;
switch (op) {
case 'add':
if (t1 === t2) { // 两个小数位数雷同
result = n1 + n2
} else if (t1 > t2) { // o1 小数位 大于 o2
result = n1 + n2 * (t1 / t2)
} else { // o1 小数位 小于 o2
result = n1 * (t2 / t1) + n2
}
return result / max;
case 'subtract':
if (t1 === t2) {result = n1 - n2} else if (t1 > t2) {result = n1 - n2 * (t1 / t2)
} else {result = n1 * (t2 / t1) - n2
}
return result / max;
case 'multiply':
result = (n1 * n2) / (t1 * t2);
return result;
case 'divide':
result = (n1 / n2) * (t2 / t1);
return result
}
}
export function add(a, b) {return operation(a, b, 'add')
}
export function subtract(a, b) {return operation(a, b, 'subtract')
}
export function multiply(a, b) {return operation(a, b, 'multiply')
}
export function divide(a, b) {return operation(a, b, 'divide')
}
export function deepCopy(obj) {if (typeof obj !== 'object') return;
var newObj = obj instanceof Array ? [] : {};
for (var key in obj) {if (obj.hasOwnProperty(key)) {newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
export function deepMixins(...objArr) {let ret = {}
function handler(key, source, ret) {let isObj = typeof source[key] == "object" // 判断是否是对象
if (isObj) {if (!ret[key]) {ret[key] = {} // 键名不存在,拷贝键名}
// 因为是对象、递归深度拷贝
Object.keys(source[key]).forEach((_key) => {handler(_key, source[key], ret[key])
})
} else {
// 是非援用类型、间接拷贝键名所对应的值
ret[key] = source[key]
}
}
// 遍历须要拷贝的对象、逐个深度拷贝
objArr.forEach((obj, idx, _self) => {Object.keys(obj).forEach((key) => {handler(key, obj, ret)
})
})
return ret
}
export function getCurRoute() {let routes = getCurrentPages() // 获取以后关上过的页面路由数组
let curRoute = routes[routes.length - 1].route // 获取以后页面路由,也就是最初一个关上的页面路由
return curRoute
}
export function base64ToSave(base64data, path = 'tmp_base64src') {return new Promise((resolve, reject) => {var [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
if (!format) {reject(new Error('ERROR_BASE64SRC_PARSE'));
}
let filePath = `${wx.env.USER_DATA_PATH}/${path}`;
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: wx.base64ToArrayBuffer(bodyData),
encoding: 'binary',
success: () => {console.log('写入胜利, 门路:', filePath);
resolve(filePath);
},
fail: err => {console.log('写入失败, fail:', err);
reject('写入失败:', err);
},
});
});
}
export function removeSave(filePath) {return new Promise((resolve, reject) => {
// 把文件删除后再写进,避免超过最大范畴而无奈写入
wx.getFileSystemManager().unlink({
filePath: filePath,
success: res => {console.log('删除胜利, 门路:', filePath);
// resolve(saveFilePath);
},
fail: err => {console.log('删除失败, err:', err);
// reject('删除失败:', err);
}
})
})
}
export function getNowTime() {const time = new Date()
let y = time.getFullYear()
let m = time.getMonth() + 1
let d = time.getDate()
let h = time.getHours()
let mi = time.getMinutes()
let s = time.getSeconds()
m = m < 10 ? `0${m}` : m
d = d < 10 ? `0${d}` : d
h = h < 10 ? `0${h}` : h
mi = mi < 10 ? `0${mi}` : mi
s = s < 10 ? `0${s}` : s
return `${y}-${m}-${d} ${h}:${mi}:${s}`
}