I have the following snippet of code in my Javascript to calculate the effective tax rate and was wondering if there is an easier way to implement this instead?
let federalTax = 0;
if (salary <= 15000){
federalTax = 0;
}
else if (salary >= 15001 && salary <= 53359){
federalTax = (salary - 15000) * 0.15;
}
else if (salary >= 53360 && salary <= 106717){
federalTax = ((salary - 15000) * 0.15) + ((salary - 53359) * 0.205);
}
else if (salary >= 106718 && salary <= 165430){
federalTax = (((salary - 15000) * 0.15) + ((salary - 53359) * 0.205)) + ((salary - 106717) * 0.26);
}
else if (salary >= 165431 && salary <= 235675){
federalTax = (((salary - 15000) * 0.15) + ((salary - 53359) * 0.205) + ((salary - 106717) * 0.26)) + ((salary - 165430) * 0.29);
}
else {
federalTax = ((((salary - 15000) * 0.15) + ((salary - 53359) * 0.205) + ((salary - 106717) * 0.26)) + ((salary - 165430) * 0.29)) + ((salary - 235675) * 0.33);
}
Receiving the correct results, but want to see if there is a more efficient way to do this.
4
Answers
First create an array consisting of smaller array where each smaller array is the upper limit for this tax bracket and the percentage/rate of tax in this bracket.
I truncate the tax to an integer number using ~~ (same effect as Math.trunc()… but shorter). The actual calculation is done like this: Loop through the brackets using map and use Math.max and Math.min to make sure we don’t get ‘negative’ taxation if you haven’t reached this bracket and that we don’t tax the income below a certain bracket in a higher bracket. Thus we get the correct part of the income taxated within the correct bracket. So now we have an array with tax you pay within each bracket for a certain income. We can sum this together to the total tax using reduce.
Since we have the data, the tax brackets, separated entirely from the logic it easy to change the brackets without changing the logic.
And what does Infinity mean you might ask? It is a special number in JavaScript meaning an infinitely large number and if you are the highest tax bracket the upper limit for that bracket is… Infinity.
You can define the margin backwards in order to reduce code and be cleaner. For example:
Pd: Is posible the values are incorrect but the idea is that.
I would recommend doing it like this. It is easier to read and can be expanded as needed with even higher salaries. Also no reason to use a range to check a value because a smaller value would have been already evaluated.
JS
This can be simplified by clamping the value to 0
… and it’s obviously becomes incorrect with 123.5% tax over 235k
You shouldn’t subtract from the same money multiple times:
(it’s possible to modify salary, byt this is much simplier)