I'm trying to build a salary tax calculator based on official numbers and rules in my country and I have this ugly monstrosity function, thousands of lines long. I'm curious to learn how I can improve this function.
I want to make it:
- Shorter, less code
- Easily extensible. Next year we will get new numbers
Numbers and cities in the code below are just examples. The actual code has about 500 if statements and 290 case rows per if statement:
export const getTax = (salary: number, city: string): number => {
if (salary >= 1701 && salary <= 1800) {
switch (city) {
case 'TOKYO': return 126;
case 'PARIS': return 136;
case 'LONDON': return 145;
case 'MADRID': return 193;
// and many more case rows
default: return 112;
}
}
if (salary >= 1801 && salary <= 1900) {
switch (city) {
case 'TOKYO': return 135;
case 'PARIS': return 186;
case 'LONDON': return 176;
case 'MADRID': return 192;
// and many more case rows
default: return 143;
}
}
if (salary >= 1901 && salary <= 2000) {
switch (city) {
case 'TOKYO': return 212;
case 'PARIS': return 209;
case 'LONDON': return 188;
case 'MADRID': return 211;
// and many more case rows
default: return 244;
}
}
// and maybe 500 more if statements