Except this code is a bit overkill.
After all, if your IF does "... && salesAmt <= 50 ...", then there is no need to test for > 50! BY DEFINITION you wouldn't REACH the next IF unless salesAmt is > 50.
Also, if you want to make it MUCH more flexible, you SHOULD base the code on the arrays, as described in the original post. Except I'd use a "unified" array insted of two separate ones.
So:
Code:
var taxBrackets = [ [50, 0.00], [100, 0.05], [250, 0.075], [500, 0.10], [1000000000, 0.20] ];
function getTaxForSale( saleamt )
{
for ( var t = 0; t < taxBrackets.length; ++t )
{
var bracket = taxBrackets[t];
if ( saleamt < bracket[0] ) return bracket[1];
}
// should never get here, unless the sale is over 1000000000
return 0.20; // or whatever the rate for over 1000000000 should be
}
A variation on that, so we don't have to worry about the 1000000000, even:
Code:
var taxBrackets = [ [50, 0.00], [100, 0.05], [250, 0.075], [500, 0.10], [null, 0.20] ];
function getTaxForSale( saleamt )
{
for ( var t = 0; t < taxBrackets.length; ++t )
{
var bracket = taxBrackets[t];
if ( bracket[0] == null || saleamt < bracket[0] ) return bracket[1];
}
}
And, of course, if you preferred to return the tax *AMOUNT* instead of just the rate, then simply do
Code:
if ( bracket[0] == null || saleamt < bracket[0] ) return saleamt * bracket[1];
instead.