Skip to content

Instantly share code, notes, and snippets.

@rtyley
Created November 11, 2022 10:31
Show Gist options
  • Save rtyley/e1b6631989e12681b96191e55c2a20cb to your computer and use it in GitHub Desktop.
Save rtyley/e1b6631989e12681b96191e55c2a20cb to your computer and use it in GitHub Desktop.
package vendingmachine
class VendingMachine {
var chocolateBar = 0
var granolaBar = 0
var totalMoney = 0.0
def buy(product: String, money: Double): String = {
if (!isProductAvailable(product)) {
s"Sorry, product $product not available"
} else if(isMoneyEnough(product, money)) {
"Not enough money"
} else completeRequest(product, money)
}
def isProductAvailable(product: String): Boolean = {
val productQuantity = {
if (product == "chocolate") chocolateBar
else if (product == "granola") granolaBar
else 0
}
productQuantity > 0
}
def isMoneyEnough(product: String, money: Double): Boolean = {
val cost = if (product == "chocolate") 1.5 else 1
money >= cost
}
def completeRequest(product: String,
money: Double): String = {
if (product == "chocolate") chocolateBar-=1 else granolaBar-=1
totalMoney += money
s"Enjoy your $product"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment