JavaScript开发需求:实现calculateTaxRate个税税率计算函数
Solution:
calculateTaxRate Function Implementation Got it, let's build this calculateTaxRate function step by step. First, we'll handle validation checks to catch invalid inputs, then map valid salary ranges to the correct tax rates based on filing status. Here's the complete implementation:
function calculateTaxRate(salary, status) { // Catch all invalid cases first if (!['single', 'joint'].includes(status) || salary < 1 || salary > 74900) { return 'Better call an accountant'; } // Determine tax rate for single filers if (status === 'single') { if (salary <= 9325) { return '10%'; } else if (salary <= 37950) { return '15%'; } else { return '25%'; } } // Determine tax rate for joint filers else { if (salary <= 18650) { return '10%'; } else { return '15%'; } } }
Breakdown of How It Works:
- Validation Layer: We first check if the
statusis either'single'or'joint', and ifsalarysits within the 1–74900 range. Any violation triggers the error message. - Single Filing Status:
- $1 to $9,325 → 10% tax rate
- $9,326 to $37,950 → 15% tax rate
- $37,951 to $74,900 → 25% tax rate
- Joint Filing Status:
- $1 to $18,650 → 10% tax rate
- $18,651 to $74,900 → 15% tax rate
Quick Test Cases:
console.log(calculateTaxRate(5000, 'single')); // Output: '10%' console.log(calculateTaxRate(40000, 'joint')); // Output: '15%' console.log(calculateTaxRate(80000, 'single')); // Output: 'Better call an accountant' console.log(calculateTaxRate(30000, 'invalid')); // Output: 'Better call an accountant'
内容的提问来源于stack exchange,提问作者Austin Loveless
相关产品推荐
相关产品推荐

