JS函数封装
在工作中我们常常会封装一些大幅度提升开发效率和性能安全的函数方法等,在此记录…
1.函数防抖 (只执行最后一次点击)
export const debounce = (fn, delay = 500) => {
let timer
return function () {
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
fn.apply(this, args)
}, delay)
}
}
2.函数节流
export const throttle = (fn, t = 200) => {
let last
let timer
return function () {
const args = arguments
const now = +new Date()
if (last && now - last < t) {
clearTimeout(timer)
timer = setTimeout(() => {
last = now
fn.apply(this, args)
}, t)
} else {
last = now
fn.apply(this, args)
}
}
}
3.四则运算(防止精度丢失)
export const math = {
/**
* @Description: 加法运算
*/
add(num1, num2) {
let baseNum, baseNum1, baseNum2;
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
return (num1 * baseNum + num2 * baseNum) / baseNum;
},
/**
* @Description: 减法运算
*/
subtract(num1, num2) {
let baseNum, baseNum1, baseNum2;
let precision; // 精度
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
},
/**
* @Description: 乘法运算
*/
multiply(num1, num2) {
let baseNum = 0;
try {
baseNum += num1.toString().split(".")[1].length;
} catch (e) {}
try {
baseNum += num2.toString().split(".")[1].length;
} catch (e) {}
return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
},
/**
* @Description: 除法运算
* @param {*} digit 保留小数,默认保留2位
*/
divide(num1, num2, digit = 2) {
let baseNum1 = 0,
baseNum2 = 0;
let baseNum3, baseNum4;
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum3 = Number(num1.toString().replace(".", ""));
baseNum4 = Number(num2.toString().replace(".", ""));
return ((baseNum3 / baseNum4) * Math.pow(10, baseNum2 - baseNum1)).toFixed(digit);
},
}