js实现纳税计算器函数

90 阅读1分钟

原理参考:juejin.cn/post/734647…

算算你每个月的税吧

/**
 *
 * @param {*} totalMonthNeedTaxDeduction 累计已纳税的收入(收入参加扣税的部分)
 * @param {*} accumulatedTaxDeduction    累计个税
 * @returns 本次需缴纳的个税
 */
function getTax(totalMonthNeedTaxDeduction, accumulatedTaxDeduction) {
  const taxRateTable = [
    { m: 36000, t: 0.03, s: 0 },
    { m: 144000, t: 0.1, s: 2520 },
    { m: 300000, t: 0.2, s: 16920 },
    { m: 420000, t: 0.25, s: 31920 },
    { m: 660000, t: 0.3, s: 52920 },
    { m: 960000, t: 0.35, s: 85920 },
    { m: Number.MAX_SAFE_INTEGER, t: 0.45, s: 181920 },
  ];
  const getFix2 = (n) => +(Math.round(n * 1000) / 1000).toFixed(2);
  for (const item of taxRateTable) {
    if (totalMonthNeedTaxDeduction < item.m) {
      return getFix2(
        totalMonthNeedTaxDeduction * item.t - item.s - accumulatedTaxDeduction
      );
    }
  }
}

/**
 *
 * @param {number[]} moneyList 每个月的收入
 * @param {number} ssd 五险一金扣除
 * @returns
 */
function calcTax(moneyList, ssd) {
  // 累计已纳税的收入
  let totalMonthNeedTaxDeduction = 0;

  // 累计个税
  let accumulatedTaxDeduction = 0;

  // 免税额
  const taxFree = 5000 + ssd;
  const target = {};
  for (let i = 1; i <= 12; i++) {
    // 本月需要纳税的收入
    let curMonthNeedTaxDeduction = Math.max(moneyList[i - 1] - taxFree, 0);

    totalMonthNeedTaxDeduction += curMonthNeedTaxDeduction;

    // 本月个税
    target[i] = getTax(totalMonthNeedTaxDeduction, accumulatedTaxDeduction);
    accumulatedTaxDeduction += target[i];
  }
  return target;
}

函数调用测试

console.log(
  calcTax(
    [
      9512, 9840, 9840, 12300, 12300, 12300, 12300, 12300, 12300, 12300, 12300,
      12300,
    ],
    1510.05
  )
);