How to calculate effective tax rate in Javascript?

Viewed 547

I currently have an array of intervals that can be used to tell me what that tax rate is for that salary.

  let tree = new IntervalTree();

  // 2020 Federal Income Tax Brackets for Single
  let singleIntervals = [
    [0, 9875],
    [9876, 40125],
    [40126, 85525],
    [85526, 163300],
    [163301, 207350],
    [207351, 518400],
    [518401, 900000000],
  ];

  tree.insert(singleIntervals[0], 10);
  tree.insert(singleIntervals[1], 12);
  tree.insert(singleIntervals[2], 22);
  tree.insert(singleIntervals[3], 24);
  tree.insert(singleIntervals[4], 32);
  tree.insert(singleIntervals[5], 35);
  tree.insert(singleIntervals[6], 37);

So I can use this let values_in_range = tree.search([10000, 10000]); to get the tax rate for someone with a salary of $10,000 which is %12. But I found out that the way federal income tax works is that you are taxed in chunks.Example.

So if I have a $50,000 salary, then "you’d pay 10% on that first $9,875 and 12% on the chunk of income between $9,876 and $40,125. And then you’d pay 22% on the rest, because some of your $50,000 of taxable income falls into the 22% tax bracket. The total bill would be about $6,800 — about 14% of your taxable income, even though you’re in the 22% bracket. That 14% is called your effective tax rate.".

What is the best way to do this?

1 Answers

Something like the following

const income = 50000;

let totalTaxes = 0;

if (income < 9875) {
  totalTaxes += income * 0.1;
}
else {
  totalTaxes += 9875 * 0.1;
  if (income < 40125) {
    totalTaxes += (income - 9875) * 0.12;
  }
  else {
    totalTaxes += (40125 - 9875) * 0.12;
    //et cetera
  }
}

edit: dynamic solution
I changed the intervals array to make it simpler: first element is the upper limit of the previous and the third element is the tax rate.
Outputs 6790

const singleIntervals = [
  [0, 9875, 0.1],
  [9875, 40125, 0.12],
  [40125, 85525, 0.22],
  [85525, 163300, 0.24],
  [163300, 207350, 0.32],
  [207350, 518400, 0.35],
  [518400, 900000000, 0.37],
];

const income = 50000;

let totalTaxes = 0;
for (const interval of singleIntervals) {
  if (income < interval[1]) {
    totalTaxes += (income - interval[0]) * interval[2];
    break;
  }
  else {
    totalTaxes += (interval[1] - interval[0]) * interval[2];
  }
}

console.log(totalTaxes);
Related