The tests
[TestFixture] public class TaxCalculatorTests { [Test] public void Tax_for_0() { var calculator = new TaxCalculator(); var tax = calculator.TaxFor(0); Assert.That(tax, Is.EqualTo(0)); } [Test] public void Tax_for_5000() { var calculator = new TaxCalculator(); var tax = calculator.TaxFor(5000); Assert.That(tax, Is.EqualTo(500)); } [Test] public void Tax_for_5800() { var calculator = new TaxCalculator(); var tax = calculator.TaxFor(5800); Assert.That(tax, Is.EqualTo(609.2).Within(0.001)); } [Test] public void Tax_for_9000() { var calculator = new TaxCalculator(); var tax = calculator.TaxFor(9000); Assert.That(tax, Is.EqualTo(1087.8).Within(0.001)); } [Test] public void Tax_for_15000() { var calculator = new TaxCalculator(); var tax = calculator.TaxFor(15000); Assert.That(tax, Is.EqualTo(2532.9).Within(0.001)); } [Test] public void Tax_for_50000() { var calculator = new TaxCalculator(); var tax = calculator.TaxFor(50000); Assert.That(tax, Is.EqualTo(15068.1).Within(0.001)); } }And the implementation
public class TaxCalculator { private readonly Tuple<decimal, decimal>[] slices = { new Tuple<decimal, decimal>(40230, 0.45M), new Tuple<decimal, decimal>(21240, 0.33M), new Tuple<decimal, decimal>(14070, 0.30M), new Tuple<decimal, decimal>(8660, 0.23M), new Tuple<decimal, decimal>(5070, 0.14M), new Tuple<decimal, decimal>(0, 0.10M), }; public decimal TaxFor(decimal sum) { if (sum == 0) { return 0; } var tax = 0M; foreach (var slice in slices) { if (sum > slice.Item1) { var amount = sum - slice.Item1; tax += amount * slice.Item2; sum -= amount; } } return tax; } }
Aucun commentaire:
Enregistrer un commentaire