Last active
February 14, 2019 16:12
-
-
Save jesusjavierdediego/ef427d5e9f67cabac7002e886ef87dde to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TaxCalculator { | |
private val taxWindows = Seq( | |
TaxForWindow(1, 5070, 10), | |
TaxForWindow(5071, 8660, 14), | |
TaxForWindow(8661, 14070, 23), | |
TaxForWindow(14071, 21240, 30), | |
TaxForWindow(21241, 40230, 33), | |
TaxForWindow(40231, Int.MaxValue, 45)) | |
def calculate(salary: Double): Double = { | |
require(salary >= 0) | |
def windowsForSalary = taxWindows.reverse.dropWhile(_.from > salary) | |
calculateInternal(salary, windowsForSalary) | |
} | |
private def taxForWindow(salary: Double, window: TaxForWindow): Double = (salary - (window.from - 1)) * window.percentage / 100 | |
private def calculateInternal(salary: Double, windows: Seq[TaxForWindow]): Double = | |
windows match { | |
case head :: tail => calculateInternal(head.from - 1, tail) + taxForWindow(salary, head) | |
case Nil => 0 | |
} | |
case class TaxForWindow(from: Double, to: Double, percentage: Double) | |
def main(args: Array[String]): Unit = { | |
println(calculate(50000)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment