Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using NUnit.Framework;
- namespace Spikes.AyendesTaxProblem
- {
- [TestFixture]
- // http://ayende.com/blog/108545/the-tax-calculation-challenge
- public class TaxCalculatorTests
- {
- private TaxCalculator calculator;
- [SetUp]
- public void SetUp()
- {
- var rates = new[]
- {
- new TaxRate( 0, 5070, 10 ),
- new TaxRate( 5071, 8660, 14 ),
- new TaxRate( 8661, 14070, 23 ),
- new TaxRate( 14071, 21240, 30 ),
- new TaxRate( 21241, 40230, 33 ),
- new TaxRate( 40231, decimal.MaxValue, 45 ),
- };
- calculator = new TaxCalculator(rates);
- }
- [TestCase( 5000.0, 500.0 )]
- [TestCase( 5800.0, 609.2 )]
- [TestCase( 9000.0, 1087.8 )]
- [TestCase( 15000.0, 2532.9 )]
- [TestCase( 50000.0, 15068.1 )]
- public void CalculateTax_SpecifiedEarnings_EqualsResult(decimal earnings, decimal expected)
- {
- var actual = calculator.CalculateTax(earnings);
- Assert.That(actual, Is.EqualTo(expected));
- }
- }
- public class TaxRate
- {
- public decimal LowerBound { get; private set; }
- public decimal UpperBound { get; private set; }
- public decimal RatePercent { get; private set; }
- public TaxRate(decimal lowerBound, decimal upperBound, decimal rate)
- {
- LowerBound = lowerBound;
- UpperBound = upperBound;
- RatePercent = rate;
- }
- }
- public class TaxCalculator
- {
- private readonly IEnumerable<TaxRate> rates;
- public TaxCalculator(IEnumerable<TaxRate> rates)
- {
- if (rates == null) throw new ArgumentNullException("rates");
- this.rates = rates;
- }
- public decimal CalculateTax(decimal earnings)
- {
- return rates
- .Where(rate => rate.LowerBound <= earnings)
- .Select(rate => rate.RatePercent * getTaxableAmount(rate, earnings) / 100m)
- .Sum();
- }
- private decimal getTaxableAmount(TaxRate rate, decimal gross)
- {
- // dirty hack for unspecified inter-rate gap.
- var min = Math.Max(0m, rate.LowerBound - 1);
- var max = Math.Min(gross, rate.UpperBound);
- var taxableAmt = max - min;
- return taxableAmt;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment