Skip to content

Instantly share code, notes, and snippets.

@jesusjavierdediego
Last active February 14, 2019 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesusjavierdediego/ef427d5e9f67cabac7002e886ef87dde to your computer and use it in GitHub Desktop.
Save jesusjavierdediego/ef427d5e9f67cabac7002e886ef87dde to your computer and use it in GitHub Desktop.
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