What can I improve on this code :
(ns interest-is-interesting)
(defn interest-rate
"Returns the interest rate based on the specified balance."
[balance]
(cond
(< balance 0 ) -3.213
(< balance 1000) 0.5
(< balance 5000) 1.621
:else 2.475 ))
(defn balance-update-amount
"Returns the amount which updates the balance."
[balance]
(let [interest-rate (bigdec (/ (interest-rate balance) 100))]
(* (abs balance) interest-rate)))
(defn annual-balance-update
"Returns the annual balance update, taking into account the interest rate."
[balance]
(+ balance (balance-update-amount balance)))
(defn amount-to-donate
"Returns how much money to donate based on the balance and the tax-free percentage."
[balance tax-free-percentage]
(if (> balance 0)
(int (* (* balance (/ tax-free-percentage 100)) 2 ))
0))Generally looks pretty good.
• If you are going to use big decimal then use it everywhere and be very careful its not being converted back into a regular double along the way.
◦ bigdecimal is probably overkill compared to double - but it's subjective and some interviewers will prefer it.
◦ (type (balance-update-amount 8.0)) => double which means the conversion to big decimal didn't really help.
• Do you really mean to convert amount into an integer - perfer (long x) over (int x) and you probably want (float x) anyway.
• You can use condp instead of cond
• This is subjective, but I prefer making my conditional statements as small as possible.
◦ (long (* (* (if (> balance 0) balance 0) (/ tax-free-percentage 100)) 2 ))
So only minor nitpicks really.
Thanks
The tests want that some outcomes are big decimals
You can also unest your (* (* => (*
That is why I convert it to a big dec
and the last one needed to be a int
Yes- but you're converting back in the next line by using (*
So you should then use big double methods for multiplication / addition etc to keep the output as bigdouble too.
Unnesting gives: (* (if (> balance 0) balance 0) (/ tax-free-percentage 100) 2 )
What is then the best way to keep it a bigdec ?
You can use the methods on the object: https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
oke, I will read that page
Thanks a lot for your feedback
No probs!