DEV Community

Discussion on: Daily Challenge #45 - Change Machine

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

that guard clause

defmodule CashMachine do                        #🎵 `goto` a CashMachine
  def change(money) do                          #🎵 to get a ticket home
    exchange(money, %{})                        #🎵 the message on the screen
  end                                           #🎵 says "don't make plans, y'all broke"

  defp exchange(0, coins), do: coins            #🎵 no, no, this can't be right
  defp exchange(coin, coins) when coin >= 25 do #🎵 I know that times is tight
    quarters = div(coin, 25)                    #🎵 I've only just been paid
    coin = rem(coin, 25)                        #🎵 three weeks, five days, do that seem
    exchange(coin, put_in(coins[25], quarters)) #🎵 right? no.
  end
  defp exchange(coin, coins) when coin >= 10 do #🎵 I scratch a livin', it ain't easy
    dimes = div(coin, 10)                       #🎵 you know it's a drag
    coin = rem(coin, 10)                        #🎵 I'm always payin', never makin'
    exchange(coin, put_in(coins[10], dimes))    #🎵 but you can't look back
  end                                           
  defp exchange(coin, coins) when coin >= 5 do  #🎵 I wonder if I'll ever get to
    nickels = div(coin, 5)                      #🎵 where I want to be
    coin = rem(coin, 5)                         #🎵 better believe it,
    exchange(coin, put_in(coins[5], nickels))   #🎵 I'm workin' for the CashMachine
  end
  defp exchange(coin, coins) when coin >= 1 do  # lyrics from "Cash Machine"
    exchange(0, put_in(coins[1], coin))         # by Hard-Fi
  end
end

Some people may say "are the comments really necessary?"

I say to them, "Is capitalism?"