Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created July 17, 2019 08:45
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 fancellu/30cb9a24bad86e387e5b378716bfd933 to your computer and use it in GitHub Desktop.
Save fancellu/30cb9a24bad86e387e5b378716bfd933 to your computer and use it in GitHub Desktop.
Scala Interest calculator based on bands, rounded to precision
case class Band(top: Double, interest: Double)
class InterestCalculator(bands: List[Band], precision: Int = 2) {
def calc(amount: Double) = {
val interest = bands.collectFirst {
case Band(top, interest) if top >= amount => interest * amount
}.getOrElse(0.0)
round(interest)
}
def round(d: Double) = {
val multiplier = math.pow(10, precision)
math.round(d * multiplier) / multiplier
}
}
import org.scalatest.{FlatSpec, Matchers}
class InterestCalculatorSpec extends FlatSpec with Matchers {
val calculator = new InterestCalculator(List(
Band(0.0, 0),
Band(1000.0, 0.01),
Band(5000.0, 0.02),
Band(Double.PositiveInfinity, 0.03)
))
"interest-calculator" should "work for £0 to £1000" in {
calculator.calc(0) shouldEqual 0
calculator.calc(1000) shouldEqual 10
calculator.calc(500) shouldEqual 5
}
it should "work for fractions" in {
calculator.calc(1) shouldEqual 0.01
calculator.calc(13.2) shouldEqual 0.13
calculator.calc(12.6) shouldEqual 0.13
}
it should "work for less than £0" in {
calculator.calc(-800) shouldEqual 0
}
it should "work for £1000 to £5000" in {
calculator.calc(3000) shouldEqual 60
calculator.calc(5000) shouldEqual 100
}
it should "work for £5000+" in {
calculator.calc(20000) shouldEqual 600
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment