My Javascript Snippets
对象排序
function sortObject(obj, recursive, sortFunc) { const result = {} Object.keys(obj).sort(sortFunc).forEach(key=>{ const curValue = obj[key] if(recursive && Object.prototype.toString.call(curValue) === "[object Object]"){ result[key] = sortObject(curValue,recursive,sortFunc) }else{ result[key] = curValue } }) return result; }
带 Progress 的 Promise.all
function promiseAll(promises) { let finishedCount = 0 let progressCb = () => {} const promisesLength = promises.length const results = new Array(promisesLength) const result = new Promise(function(resolve, reject) { promises.forEach((val, idx) => { Promise.resolve(val).then( function(res) { finishedCount++ results[idx] = res progressCb(finishedCount, results) if (finishedCount === promisesLength) { return resolve(results) } }, function(err) { return reject(err) }, ) }) }) result.progress = cb => { progressCb = cb return result } return result } // 用法 Promise.prototype.all = promiseAll var p1 = Promise.resolve(1) var p2 = Promise.resolve(2) var p3 = Promise.resolve(3) Promise.all([p1, p2, p3]) .progress((i, j) => { console.log(i, j) }) .then(function(results) { console.log(results) // [1, 2, 3] })
计算个税
/** * 计算个税 * @param taxableIncome {number} 0 需缴税的收入(扣除五险一金等) * @param startLine {number} 5000 起征点 * @return {afterTax, tax} 税和缴税后的收入 */ function calTax(taxableIncome = 0, startLine = 5000) { // configs const levels = [0, 3000, 12000, 25000, 35000, 55000, 80000]; const taxRates = [0, 0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45]; const deductions = [0, 0, 105, 555, 1005, 2755, 5505, 13505]; const toBeTaxedIncome = taxableIncome - startLine; const levelIdx = levels.findIndex(level => level > toBeTaxedIncome); const tax = toBeTaxedIncome * taxRates[levelIdx] - deductions[levelIdx]; const afterTax = taxableIncome - tax; return { afterTax, tax }; }
计算五险一金
/** * 计算五险一金 * @param income {number} 0 收入 * @param maxBase {number} 21400 最高基数,根据不同地方来改变,此为上海市 * @return {myFees, cFees} {Array,Array} 分别是自己的缴费和公司的缴费,数组各元素分别代表: * myFees: [总共 养老 医疗 失业 公积金] * cFees: [总共 养老 医疗 失业 公积金 工伤 生育] */ function calInsurances(income, maxBase = 19512) { // configs // 我的费率:养老 医疗 失业 公积金 const myRates = [0.08, 0.02, 0.005, 0.07]; // 公司费率:养老 医疗 失业 公积金 工伤 生育 const cRates = [0.2, 0.1, 0.005, 0.07, 0.003, 0.01]; // 添加总费率 myRates.unshift( myRates.reduce((totalRate, curRate) => totalRate + curRate, 0) ); cRates.unshift(cRates.reduce((totalRate, curRate) => totalRate + curRate, 0)); const base = Math.min(income, maxBase); const myFees = myRates.map(rate => (base * rate).toFixed(2)); const cFees = cRates.map(rate => (base * rate).toFixed(2)); return { myFees, cFees }; }
相关推荐
前端开发Kingcean 2020-06-11
前端开发Kingcean 2020-05-29
89500297 2020-04-29
往后余生 2020-09-17
CXsilent 2020-09-16
webgm 2020-08-16
Lophole 2020-06-28
sqliang 2020-06-14
xcguoyu 2020-06-13
徐建岗网络管理 2020-06-11
cbao 2020-06-10
yezitoo 2020-06-06
bigname 2020-06-04
xiaofanguan 2020-05-29
ELEMENTS爱乐小超 2020-05-28
皖林 2020-05-11
wbczyh 2020-05-03