Skip to content

Instantly share code, notes, and snippets.

@rjchatfield
Created December 6, 2014 09:18
Show Gist options
  • Save rjchatfield/40871b40067dc20ad039 to your computer and use it in GitHub Desktop.
Save rjchatfield/40871b40067dc20ad039 to your computer and use it in GitHub Desktop.
FP solve the Change Problem
#
# FP solve the Change Problem
# eg. myChange = calcChange(cost, myPayment)
#
# Used in fold() to build change object
# Should be nested in calcChange, but is lifted for cleanliness
coinAccStructure = (acc, coin) ->
change = acc["payment"]
acc[coin] = change % coin
acc["payment"] = change / coin
acc
# Curried calculator
calcChange = (coins) -> (cost, payment) ->
coins.fold(coinAccStructure, {"payment": payment}).omit "payments"
# Initalisated calculator for Australian coins
auCoins = [2, 1, .5, .2, .1, .05]
calcAuChange = calcChange(auCoins)
# Use
cost = 5.20
payment = 10.00
change = calcAuChange(cost, payment)
@atcruice
Copy link

atcruice commented Dec 7, 2014

Had a crack at it this morning, take a look at my fork.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment