Undefined Recursion in Tax Calculation
In this recursive tax calculation function:
function taxes(tax, taxWage) { var minWage = firstTier; //defined as a global variable if (taxWage > minWage) { //calculates tax recursively calling two other functions difference() and taxStep() tax = tax + difference(taxWage) * taxStep(taxWage); var newSalary = taxWage - difference(taxWage); taxes(tax, newSalary); } else { returnTax = tax + taxWage * taxStep(taxWage); return returnTax; } }
the recursion fails to terminate. Specifically, the issue lies in the arm of the function that invokes the recursive call:
if (taxWage > minWage) { // calculates tax recursively calling two other functions difference() and taxStep() tax = tax + difference(taxWage) * taxStep(taxWage); var newSalary = taxWage - difference(taxWage); taxes(tax, newSalary); }
Here, the function does not return any value or set the returnTax variable. When a function does not return explicitly, it defaults to returning undefined. Consequently, the recursion continues indefinitely, leading to undefined results.
To fix this issue, you should modify this part of the code as follows:
if (taxWage > minWage) { // calculates tax recursively calling two other functions difference() and taxStep() tax = tax + difference(taxWage) * taxStep(taxWage); var newSalary = taxWage - difference(taxWage); return taxes(tax, newSalary); }
This change ensures that the function returns the result of the recursive call, properly propagating the values up the recursion chain.
The above is the detailed content of Why Does This Recursive Tax Calculation Function Result in Undefined Recursion?. For more information, please follow other related articles on the PHP Chinese website!