I got a code challenge from exercism title: Interest is interesting. I solved the questions with extra challenge from myself: use functional approach as much as possible. However, I found my last function use two mutable variables.
package interest
import "math"
// InterestRate returns the interest rate for the provided balance.
func InterestRate(balance float64) float32 {
switch {
case balance < 0:
return 3.213
case balance < 1000:
return 0.5
case balance < 5000:
return 1.621
default:
return 2.475
}
}
// Interest calculates the interest for the provided balance.
func Interest(balance float64) float64 {
if balance < 0 {
return -math.Abs(balance) * float64(InterestRate(balance)) / 100.0
}
return math.Abs(balance) * float64(InterestRate(balance)) / 100.0
}
// AnnualBalanceUpdate calculates the annual balance update, taking into account the interest rate.
func AnnualBalanceUpdate(balance float64) float64 {
return balance + Interest(balance)
}
// YearsBeforeDesiredBalance calculates the minimum number of years required to reach the desired balance:
func YearsBeforeDesiredBalance(balance, targetBalance float64) int {
year := 0
for balance < targetBalance {
balance = AnnualBalanceUpdate(balance)
year++
}
return year
}
Is there any more 'functional programming' approach for my codes?